OKTech Web Services

OKTech Web Services

by Justin Filip -
Number of replies: 328
Hi,

I'm starting this new discussion to talk about the web services interface written by Open Knowledge Technologies (the code at /contrib/patches/ws/ or http://moodle.org/mod/data/view.php?d=13&rid=573).

Some people are trying to get this to work with languages other than PHP recently and have been discovering things. Also some people want to add functionality to this and I want to discuss that progress here. I also have some ideas for an overhaul of the existing code.

Anyway, if you're using this code already, want to use it, or want to add functionality to the code: this is the place to talk about it.

Thanks!
Average of ratings: -
In reply to Justin Filip

Re: OKTech Web Services

by Catalin Maican -
Hi,

I have successfully created a proxy using (reduced/cut out) the attached file. Now, when I try to login from a Windows Forms (VS2005) client I get the error :

"Client found response content type of 'text/html', but expected 'text/xml'.
The request failed with an empty response."

Is there any possibility to see the error message(s) returned by the web service ?

Thanks,
Catalin

PS. I've successfully enabled the WS to work with the latest Moodle 1.6 and the call is made to this version, as you suggested.
In reply to Catalin Maican

Re: OKTech Web Services

by Justin Filip -
Yeah, if you're getting HTML in the response it means that something is causing an error within Moodle itself which isn't being caught by the server code.

If you change line 30 in /ws/soapserver.php to define('DEBUG', true); it will dump debugging output into a file called 'debug.out' in your configured $CFG->dataroot directory for Moodle.

You can also output the received data in your client (if you have access to the response before your client dies). Often you can tell what happened by seeing some Moodle HTML code and an error message. I've tried to wrap any Moodle API calls that could possibly throw an HTML error response in an output buffer and if the buffer contains an error, an appropriate SOAPFault will be returned from the server. However, I probably don't have all the API calls WS safetied in this manner.
In reply to Justin Filip

Re: OKTech Web Services

by Catalin Maican -
I don't have access until tomorrow at the development computers (at work) but I found two free HTTP/SOAP/WSDL testers and debuggers:

1. SOAPUI - http://www.soapui.org/
2. StrikeIron WS Analyzer for Windows - http://www.strikeiron.com/tools/tools_analyzer_windows.aspx

I hope this tools might help anyone who wants to debug Web Service...

Catalin
In reply to Catalin Maican

Re: OKTech Web Services

by Catalin Maican -
Hi,

for anyone who's interested... I have a small Windows Forms project that connects to a remote Moodle 1.6... it only uses Login and GetUser methods, but you'll figure out the rest smile

SoapUI was a great helper tool for finding out the errors from the modified WSDS I used.

I found something interesting.... GetUser method uses the "idnumber" column in the DB... how can I set this field in a normal way/Moodle user-interface way?
Also, wouldn't be more useful a GetUser method that would use the "username" instead of "idnumber"?

Catalin
In reply to Catalin Maican

Re: OKTech Web Services

by Justin Filip -
The 'user.idnumber' field is accessible from the user profile screen in Moodle (it's at the bottom of the page, in the optional fields section). This value is lockable by site admins so that they can assign a value to a user which the user can't change (i.e. an institutionally unique student ID number). This was initially how we decided to design it for the client we built this extension for but I think allowing the use of either the 'idnumber' or 'username' fields makes a lot of sense for this call.
In reply to Catalin Maican

Re: OKTech Web Services

by abdelaziz ouadah -
Hello, i have had the same problem : when i call the http://127.0.0.1/wspp/wsdl_pp.php , i have the wsdl file coorectly. but the end point no response. i tried the http://127.0.0.1/moodle/wspp/service_pp.php, but i have had 404 error page. also when i pull up http://127.0.0.1/wspp/service_pp.php in my browser and it's a blank page. also i am using SOAPUI to test services, (with the same end point:http://127.0.0.1/wspp/service_pp.php). i sent the soap message: admin test and i have got this response: HTTP/1.1 200 OK Date: Tue, 27 Oct 2009 12:25:49 GMT Server: Apache/2.2.8 (Win32) mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 X-Powered-By: PHP/5.2.5 Set-Cookie: MoodleSession=7bc0688d791e8100ea1b1f1205a8bcfa; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Set-Cookie: MoodleSessionTest=W6H1z8zKAW; path=/ Content-Length: 0 Content-Type: text/html any suggestions please. thanx.
In reply to abdelaziz ouadah

revision 1.6.2 is out

by Patrick Pollet -
hello,

Revision 1.6.2 has been committed today to Moodle 's CVS and project's page http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews

  1. Moodle 1.9.7 password policy compatible
  2. cleaned code from Lille University ( internationalization, capabilities, gradebook compatible )
  3. added operation get_assignment_submissions allowing download of files submitted by students on assignments.
Merry Christmas and Happy New Year.




Average of ratings: Useful (1)
In reply to Patrick Pollet

Re: revision 1.6.2 is out

by Patrick Pollet -
Please consult the file INSTALL.TXT for a working example of usage.
By running the following command from the wspp/clients directory

php ../wsdl2php.php http://yourmoodle/wspp/wsdl_pp.php

you will find in tests directory a sample PHP script for all 112 supported operations

as far as add_user is concerned the generated test script will be something like


<?php
require_once ('../MoodleWS.php');

$moodle=new MoodleWS();
require_once ('../auth.php');
/**test code for MoodleWS: add on course
* @param integer $client
* @param string $sesskey
* @param userDatum $user
* @return editUsersOutput
*/

$lr=$moodle->login(LOGIN,PASSWORD);
$user= new userDatum();
$user->setAction('');
$user->setId(0);
$user->setConfirmed(0);
$user->setPolicyagreed(0);
$user->setDeleted(0);
$user->setUsername('');
$user->setAuth('');
$user->setPassword('');
$user->setPasswordmd5('');
$user->setIdnumber('');
$user->setFirstname('');
$user->setLastname('');
$user->setEmail('');
$user->setEmailstop(0);
$user->setIcq('');
$user->setSkype('');
$user->setYahoo('');
$user->setAim('');
$user->setMsn('');
$user->setPhone1('');
$user->setPhone2('');
$user->setInstitution('');
$user->setDepartment('');
$user->setAddress('');
$user->setCity('');
$user->setCountry('');
$user->setLang('');
$user->setTimezone(0);
$user->setLastip('');
$user->setTheme('');
$user->setDescription('');
$user->setMnethostid(0);
$res=$moodle->add_user($lr->getClient(),$lr->getSessionKey(),$user);
print_r($res);
print($res->getUsers());

$moodle->logout($lr->getClient(),$lr->getSessionKey());

?>

so just fill the blanks and comment out (or remove) lines concerning non mandatory attributes you do not want to set ...



Another way is to use the openSource soapUI software that allow testing of web services with a graphical interface ...
It will build the needed requests from the wsdl file sent by the Moodle server... if you understand some french you could peek
at my video demo at http://cipcnet.insa-lyon.fr/moodle/file.php/1/soapui_demo.flv
In reply to Patrick Pollet

Re: revision 1.6.2 is out

by Leonel Lopez -

Hi, Patrick

Hope you can help me this case, I try a test add_usser (http://logosoft.us.to/ws/wspp/clients/tests/test_add_user.php) but have problem I get a error:


Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://localhost/ws/wspp/wsdl_pp.php' in C:\wamp\www\ws\wspp\clients\MoodleWS.php:389 Stack trace: #0 C:\wamp\www\ws\wspp\clients\MoodleWS.php(389): SoapClient->SoapClient('http://localhos...', Array) #1 C:\wamp\www\ws\wspp\clients\tests\test_add_user.php(6): MoodleWS->MoodleWS() #2 {main} thrown in C:\wamp\www\ws\wspp\clients\MoodleWS.php on line 389

Have you any idea about it?

Thanks

 

 

 

 

In reply to Leonel Lopez

Re: revision 1.6.2 is out

by Patrick Pollet -

Hi Lenoard,

1)   wspp MUST be uznipped in Moodle's root directory and NOT in a ws subdirectory. See file INSTALL for further instructions.

2) scripts in directory wspp/clients/tests are meant to be edited AND used on the command line , not by the Web.

Cheers.

In reply to Patrick Pollet

Re: revision 1.6.2 is out

by udhayakumar R -

How to create a new web service function, and a class. 

i created a method in the mdl_soapserverBindingstub()

i just created a class WelcomeMessage();

and a method get_message(); in Mdl_SoapserverBindingStub()

but i am getting a error like below

 

02-21 18:05:22.940: W/System.err(1153): java.lang.ClassCastException: org.ksoap2.SoapFault
02-21 18:05:22.940: W/System.err(1153): at core.ws.Mdl_soapserverBindingStub.get_message(Mdl_soapserverBindingStub.java:43)
02-21 18:05:22.940: W/System.err(1153): at com.thinkbox.padasala.lemon.ViewCourse.getcourseContent(ViewCourse.java:88)
02-21 18:05:22.940: W/System.err(1153): at com.thinkbox.padasala.lemon.ViewCourse.onCreate(ViewCourse.java:32)
02-21 18:05:22.940: W/System.err(1153): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-21 18:05:22.940: W/System.err(1153): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
02-21 18:05:22.940: W/System.err(1153): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
02-21 18:05:22.940: W/System.err(1153): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-21 18:05:22.940: W/System.err(1153): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
02-21 18:05:22.940: W/System.err(1153): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 18:05:22.940: W/System.err(1153): at android.os.Looper.loop(Looper.java:123)
02-21 18:05:22.940: W/System.err(1153): at android.app.ActivityThread.main(ActivityThread.java:3647)
02-21 18:05:22.940: W/System.err(1153): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 18:05:22.940: W/System.err(1153): at java.lang.reflect.Method.invoke(Method.java:507)
02-21 18:05:22.940: W/System.err(1153): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-21 18:05:22.940: W/System.err(1153): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-21 18:05:22.940: W/System.err(1153): at dalvik.system.NativeStart.main(Native Method)

 

please help me.

In reply to Justin Filip

Re: OKTech Web Services

by Frédéric Mathiot -
Do anybody know which is the best way to securise comunication between client and web service ? Maybe using HTTPS, but there are maybe some other solutions.
In reply to Frédéric Mathiot

Re: OKTech Web Services

by Justin Filip -
I think that HTTPS is the best (and simplest) way to secure all the communications -- both initial authentication and any follow-up communications. I know that SOAP has support for an authentication header that allows you to supply a username and password with every client request of the server but the data itself is still being transmitted in the clear (including the credentials with every request).
In reply to Justin Filip

Re: OKTech Web Services

by Marko Novakovic -
I have been using moodle for my school project. I had to change the field "idnumber" to "username", i guess that field is used by professors, and it's empty at my localhost instalation. That is not the only thing i had to change to make web services to work. I am using 1.6.5! Anyone had these problems? I am using OKTech Web Services, of course.

My question is:
How can i modify existing web services, so i can operate with quizzes?
I mean, how big project would it be? I am not really an expert, (not at the this moment smile )

Any working solution out there? So far i haven't found any! SOAP + WSDL
In reply to Justin Filip

Re: OKTech Web Services

by Frédéric Mathiot -
The problem for this solution is that HTTPS must be enabled by the Moodle administrator, and we can't control that...
WS-Security is a model, which permit to protect communication, with username and password system, but also data crypting. It works for Java and .net, but I'm searching for a PHP solution..... harder smile
In reply to Frédéric Mathiot

Re: OKTech Web Services

by Catalin Maican -
Questions:

1.about xsd:all vs. xsd:add

Replacing xsd:add with xsd:all I could successfully create a proxy using Visual Studio 2005 for the original/OO version. What is the difference between the two of them ?


2. This version of Web service it is very useful. However, it does not implement a series of basic methods like: GetUserByUsername, GetRolesByUser, GetModulesByUser, GetCourserByUser/GetEnroledCoursesByUser, quizes, forums, roles/security etc.

I do not know PHP at all because I could have helped in this development, because I really need these....

Catalin
In reply to Catalin Maican

Re: OKTech Web Services

by Justin Filip -
Hmm.... not particularly sure about "xsd:all" vs. "xsd:add". The WSDL that is in wsdl.php was generated by NuSOAP (the PHP SOAP extension written in PHP). So I defined the structures with PHP and then copied the generated WSDL to the PHP file to be able to process some things -- like the URLs pointing to the Moodle site.

I imagine there are probably other tweaks that could / should be made to the WSDL to make it easier to use with other clients.

And as far as extending the web services to add the extra functionality it's definitely possible but just a matter of when I'll get some spare time to actually work on it.
In reply to Justin Filip

Re: OKTech Web Services

by Marko Novakovic -
@Justin Filip

I think i could find some extra time to expand OKTech Web Services. Only thing that could be a problem is that i am not really a good PHP programmer, maybe 2-3 years of expirience, but mostly fun. The other thing is the time needed for expanding. So your advices could be helpfull.

This is what i need and am willing to spend time at: Quiz operations (add, edit, delete). I guess this is worthless without also operations with questions.

I can see you know about this WS component, so could you tell me where should be my first point for research?

This is my idea, but i think your advice is really welcome:
Playing with moodle to see exactly what is the idea of quizz-related activities, then researching the database schema, then writing those functions in PHP and finally implementing with WS?
In reply to Marko Novakovic

Re: OKTech Web Services

by Justin Filip -
Marko,

A good starting point would be to look at the quiz module API in /mod/quiz/lib.php. Chances are all the functions you would want to have already exist there and a web services wrapper would just need to be written around them.

You can browse through the cross-referenced Moodle source (for 1.7...) here:

http://xref.moodle.org/

But playing around with that code in a test file and some sample data in your test site is a good way to figure out what's going on and what the database entries actually mean.
In reply to Frédéric Mathiot

Re: OKTech Web Services

by Michal Hruby -
Hi,
i want ask if someone have experience with implementing WS-Security to existing OKTech Web Services. I found solution WSO2 WSF/PHP on website http://wso2.org/projects/wsf/php/features, which support WS-Security. So if someone have some tips, guides i will be grateful.

Average of ratings: Useful (1)
In reply to Justin Filip

Re: OKTech Web Services (Updated)

by Justin Filip -
I just updated the Contrib CVS with some new WS code (should be available for anonymous download in a couple hours from http://download.moodle.org/download.php/patches/ws.zip):

Modified to fix compatibility issues with:
- MS Visual Studio IDE's and Java?
- conflicts with PHP5 built-in SOAP support classes

(Changed the soapserver class name to 'mdl_soapserver', fixing WSDL appropriately.)

Added a new field to the getUser method 'idfield' which specifies which database field the 'userids' array values are being compared against (i.e. 'idnumber' or 'id').

I implemented two changes based on feedback from Catalin Maican: the WSDL fix changing 'xsd:all' to 'xsd:add' and the new argument to the 'getUser' method for people not using the 'idfield' value on their user records.

Hopefully this will solve issues with people getting this working with non-PHP languages and also keeping the (extendable) object-oriented structure in place.
In reply to Justin Filip

Re: OKTech Web Services (Updated)

by Mahesh Thoppae -

Thanks Justin for all your help.

I have tried the latest WS code (which contains Lib directory) using Visual Studio 2005. Still I am getting the same error. Here is the error.

-----------

The document at the url http://<ServerName>/moodle18/ws/service.php?type=soap&wsdl was not recognized as a known document type.
The error message from each known type may help you fix the problem:
- Report from 'DISCO Document' is 'Discovery document at the URL http://<ServerName>/moodle18/ws/service.php?type=soap&wsdl could not be found.'.
  - The document format is not recognized.
- Report from 'WSDL Document' is 'There is an error in XML document (237, 4).'.
  - The element was not expected in this context: <xsd:add xmlns:xsd='http://www.w3.org/2001/XMLSchema'>..</xsd:add>;. Expected elements: http://www.w3.org/2001/XMLSchema:annotation, http://www.w3.org/2001/XMLSchema:complexContent, http://www.w3.org/2001/XMLSchema:simpleContent, http://www.w3.org/2001/XMLSchema:group, http://www.w3.org/2001/XMLSchema:sequence, http://www.w3.org/2001/XMLSchema:choice, http://www.w3.org/2001/XMLSchema:all, http://www.w3.org/2001/XMLSchema:attribute, http://www.w3.org/2001/XMLSchema:attributeGroup, http://www.w3.org/2001/XMLSchema:anyAttribute.
- Report from 'XML Schema' is 'The root element of a W3C XML Schema should be <schema> and its namespace should be 'http://www.w3.org/2001/XMLSchema'.'.

---------------

Justin, I know you have modified WSDL.PHP, from xsd:add to xsd:all, but still that wasn't changed when you browse http://<ServerName>/moodle18/ws/service.php?type=soap&wsdl this url. This same url I am using for access the web service. So my guess is the WSDL file is generated dynamically, which hasn't changed. This is just my guess, I don't have any insight.

Please help me to resolve the issue.

Thanks,

Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated)

by Justin Filip -
Mahesh,

You are right. The URL you are using is the URL that will allow the NuSOAP PHP extension to dynamically generate the WSDL document. That was what I initially based the WSDL file off of. Try using wsdl.php instead.

The ability to use service.php?type=spoap&wsdl is really for debugging purposes (i.e. changing something in the WSDL structure without updating wsdl.php).

If you were adding new function calls, then using the debugging WSDL URL would make sense.

I'll see if I can get the WSDL generated by NuSOAP to be adjusted somehow (maybe modifying the NuSOAP code directly, if necessary). But for now, try using wsdl.php and see if that works (it should be fine).
In reply to Justin Filip

Re: OKTech Web Services (Updated)

by Mahesh Thoppae -

Justin,

I tried to use wsdl.php, instead of giving webservice methods it is trying to download the file and when I click open then it is giving error, ie. "Internet explorer cannot download wsdl.php from <servername>" (I don't know how to attach the error screenshot)

Before we go further, I want to make sure what I did to install the web service. I have copied WS folder under moodle virtual directory. So the structure is Server->Moodle->WS folder. Under WS folder all the files and lib folder are there.

Thanks,

Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated)

by Justin Filip -
Yes, you've installed it correctly. It's very simple and just needs to be unpacked into the root of the Moodle install.

Now, is this the exact error you're receiving (or with wsdl.php when using that filename)?

Report from 'DISCO Document' is 'Discovery document at the URL http://<ServerName>/moodle18/ws/service.php?type=soap&wsdl could not be found.'.

Because it looks to me like you're not entering a server name there. If the Visual Studio client is running on the same machine as the server running Moodle then you'd want to use localhost as the server name. If it's a machine on your local network, you should just be able to use a hostname or IP address (i.e moodleserver or 10.0.0.1). And if the server is running somewhere out on the Internet, then just use the same hostname that you would use to actually access the Moodle site directly (i.e. www.mymoodlesite.net).

The error is saying the document can't be found and that seems to be why.

Now, I know that Catalan is using Visual Studio .NET so perhaps he can offer some assistance with setting up the Visual Studio side of things?
In reply to Justin Filip

Re: OKTech Web Services (Updated)

by Mahesh Thoppae -

Justin, I am using the servername. The interesting thing is when I use Internet explorer to access the ws/wsdl.php file it says internet explorer cannot download wsdl.php. If I do it from Mozilla Firefox browser it is generating moodlews.wsdl file. So Visual Studio tied up with Internet explorer. If I copy moodlews.wsdl file into ws directoy in Moodle server, and try to access the moodlews.wsdl then it is showing without error, but when I add the reference then it is giving error. The error is "There was an error generating xml document".

Guys, any help will be really appreciated.

-Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated)

by Justin Filip -
That's very strange. Here's an idea, though. If Firefox allows you to view the WSDL file, download that generated file and put it in the /ws/ directory on your Moodle server. Then point your client at /moodle18/ws/moodlews.wsdl and see if THAT works?

It's worth a shot. The wsdl.php script is just meant to fill in the URL to your server so the WSDL is custom for each server it's installed on (and doesn't require any hand editing).
In reply to Justin Filip

Re: OKTech Web Services (Updated)

by Mahesh Thoppae -

Justin, 

 If I copy moodlews.wsdl file into ws directoy in Moodle server, and try to access the moodlews.wsdl then it is showing without error, but when I add the reference then it is giving error.

The error is "There was an error generating xml document".

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated)

by Mahesh Thoppae -

When I use command prompt tool it is giving following error message. I don't know it helps to find this issue or not.

----------

C:\Program Files\Microsoft Visual Studio 8\VC>wsdl /l:CS http://kdt-us-ssevern2/
moodle18/ws/moodlews.wsdl
Microsoft (R) Web Services Description Language Utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Warning: This web reference does not conform to WS-I Basic Profile v1.1.
R2706: A wsdl:binding in a DESCRIPTION MUST use the value of "literal" for the u
se attribute in all soapbind:body, soapbind:fault, soapbind:header and soapbind:
headerfault elements.
  -  Input element soapbind:body of operation 'mdl_soapserver.login' on portType
 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.
  -  Output element soapbind:body of operation 'mdl_soapserver.login' on portTyp
e 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.
  -  Input element soapbind:body of operation 'mdl_soapserver.logout' on portTyp
e 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.
  -  Output element soapbind:body of operation 'mdl_soapserver.logout' on portTy
pe 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.
  -  Input element soapbind:body of operation 'mdl_soapserver.edit_user' on port
Type 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.

  -  Output element soapbind:body of operation 'mdl_soapserver.edit_user' on por
tType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'
.
  -  Input element soapbind:body of operation 'mdl_soapserver.get_user' on portT
ype 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.

  -  Output element soapbind:body of operation 'mdl_soapserver.get_user' on port
Type 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.

  -  Input element soapbind:body of operation 'mdl_soapserver.edit_course' on po
rtType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl
'.
  -  Output element soapbind:body of operation 'mdl_soapserver.edit_course' on p
ortType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsd
l'.
  -  Input element soapbind:body of operation 'mdl_soapserver.get_course' on por
tType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'
.
  -  Output element soapbind:body of operation 'mdl_soapserver.get_course' on po
rtType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl
'.
  -  Input element soapbind:body of operation 'mdl_soapserver.get_grades' on por
tType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'
.
  -  Output element soapbind:body of operation 'mdl_soapserver.get_grades' on po
rtType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl
'.
  -  Input element soapbind:body of operation 'mdl_soapserver.enrol_students' on
 portType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/w
sdl'.
  -  Output element soapbind:body of operation 'mdl_soapserver.enrol_students' o
n portType 'MoodleWSBinding' from namespace 'http://kdt-us-ssevern2/moodle18/ws/
wsdl'.

For more details on the WS-I Basic Profile v1.1, see the specification
at http://www.ws-i.org/Profiles/BasicProfile-1.1.html.

Error: Initialization failure. Please review input options and documents for val
idity.
  - Invalid wsd:arrayType syntax: 'http://www.w3.org/2001/XMLSchema:string'.

If you would like more help, please type "wsdl /?".

--------------

In reply to Justin Filip

Re: OKTech Web Services (Updated again)

by Justin Filip -
I just checked in some more changes to the Contrib code to allow for greater compatibility with the WSDL file being used (both the one generated by NuSOAP and the static wsdl.php versions).

This should fix all the compatibility errors with Visual Studio.

The code is still available from the same location (with some delay for anonymous CVS access):

http://download.moodle.org/download.php/patches/ws.zip

Check the first line of /ws/wsdl.php to verify that you have the latest version, it should have the following CVS ID info:
$Id: wsdl.php,v 1.3 2007/04/16 22:04:26 jfilip Exp $
In reply to Justin Filip

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Wow!!! Finally you did it. Now I don't get any error. I am using http://<servername>/moodle/ws/service.php?type=soap&wsdl and VS 2005 created proxy for that.

Just curious what was holding?

Thanks for your help.

-Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Justin Filip -
Glad to hear it!

In the output, the following error code:

R2706: A wsdl:binding in a DESCRIPTION MUST use the value of "literal" for the use attribute in all soapbind:body, soapbind:fault, soapbind:header and soapbind:headerfault elements.

was explained in the page link at the bottom of the output. So I made a change based on that error and also another item that had been found before (but not implemented) which I believe a warning in your console output reminded me of: changing the xsd:string type to xsd:string[].
In reply to Justin Filip

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Sorry to bother you again.

Here is couple of issues I am seeing.

VS2005 didn't give the error. But when I try to access the page without using moodle webservice I am getting this error. VS just added the reference into the configuration section.

-----------------

Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Schema item 'complexType' named 'userRecord' from namespace 'http://kdt-us-ssevern2/moodle18/ws/wsdl'.

Source Error:

[No relevant source lines]


Source File: /EdServices/App_WebReferences/MWS/    Line: 1

---------------------------
Usually when we add webservice into VS it will generate three files: wsdl, disco, discomap. But in this case it created only wsdl and discomap only. I don't see disco file (discovery information). So I ran the command prompt tool again and got this error.

-----------------------------

C:\Program Files\Microsoft Visual Studio 8\VC>wsdl /l:CS http://kdt-us-ssevern2/
moodle18/ws/service.php?type=soap&wsdl
Microsoft (R) Web Services Description Language Utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Error: There was an error processing 'http://kdt-us-ssevern2/moodle18/ws/service
.php?type=soap'.
  - The HTML document does not contain Web service discovery information.

----------------------------------

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Justin,

Here is the wsdl file generated from VS 2005. I hope this helps to fix the error. This file shows some xml error. I don't know, is that matter or not. just incase I have attached this file.

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Justin Filip -
I don't understand why VS is generating a WSDL file. You are trying to write a client that will use the methods exposed via the Moodle WSDL file, right?

I don't see why a client needs to generate a WSDL file.

If you're writing a client you should just be able to point VS at the WSDL file and it should create a proxy for to handle the method calls / returns from the service on the Moodle end. A client doesn't create a WSDL file, it consumes one.

My PHP test client (/ws/ws-test.php) included with the code was written without any graphical tools and it was just a couple function calls to create the connection and the proxy object.
In reply to Justin Filip

Re: OKTech Web Services (Updated again)

by Catalin Maican -
Hi,

I didn't have any spare time lately.

Anyway, today I had some time and I found some errors in the WSDL file generated by the WSDL.php:
- not all the strings had to be "string[]" but only those that define an array
- because of the errors I had to replace the soap:body use="literal" to soap:body use="encoded" at the end of the file, as it was in the previous versions. (if it remains as " soap:body use="literal" ", VS requires for the mdl_soapserverget_user method the 3rd parameter to be of type getUserInput / XML and not an Array of type string...)

I attached the corrected file...

BUT... when I run the app using the new file and WS, I get the following error "method 'mdl_soapserverlogin' not defined in service"

Thanks,
Catalin

In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Patrick Pollet -
Hello Catalin,

You new version of wsdl.php DOES fix two of the problems I was having when trying to port OKTech WS to Moodle 1.7/1.8 (with Php, Java or Python clients) . We need them to link Moodle's database to French educational portals ...

1) if the list of userids to pass to get_user was an array, I received errors (invalid user ID) since it was sent as an array of array "Array
(
[item] => Array
(
[0] => 2319241
[1] => 300015
)

)"
but if it was a single value, it was sent as an array of 1 string.
string(31) "Array
(
[item] => 2319241
)"



2) same problem fixed with a list of courses to retrieve

3) changing "literal" to "encoded" fixed a lot of XML payload parse errors with "french caracters" in course description (& ' " ...)


Since the security model have dramatically changed between 1.6 and 1.7 (roles ...) most of the functions in server.class.php that check user's rights (isteacher,isadmin ...) have to be rewritten. I am getting close of something useable ...

I am attaching a "working" server.class.php that allow the test script (ws-test.php) to run against a Moodle 1.7.2 server.

I hope that in few days I can submit here a working version for the new Moodles with my basic needs fullfilled :

GetUserByUsername,
GetCourseByUser,
GetCourseTeachedByUser,
GetUsersByCourse
GetLastChangesByCourse

Justin will then decide what to do with it wink

Cheers.


In reply to Patrick Pollet

Re: OKTech Web Services (Updated again)

by Catalin Maican -
Hi,

I get the error "method 'mdl_soapserverlogin' not defined in service". Did you see/get this error ?

[edit] Also, it is interesting that mdl_soapserverlogin _does_ work in SoapUI tool, so what should I do ?

Catalin
In reply to Patrick Pollet

Re: OKTech Web Services (Updated again)

by Justin Filip -
Patrick,

Thanks. I'll definitely add any new functions to the server classes that anyone here writes.

I'll take the changes you made for 1.7 and higher where you're directly calling isadmin/isteacher/isstudent, etc. and put them into proper roles/capabilities calls. The functions you used are deprecated and will be removed at a later date (they're still in 1.8, though).
In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Thanks Catalin for your php file. It removes the errors when I add into VS 2005. And also when I tried SoapUI tool, to call mdl_soapserver.login with passing parameters, it didn't give any error but got response for 0 bytes, that means it is not returning any thing from webservice.

Catalin, what moodle version do you have success with this web service. If you have success with 1.6 version please send me the wsdl file. It will help me to proceed some. I saw your reply from other thread yesterday only.  I thought this thread is appropriate to reply.

I am stuck with this web service last three days. Please help me.

Thanks,

Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Catalin Maican -
Hi Mahesh,

I used the attached file with moodle 1.6. I did not test all the functions but only the Login/Logout, GetUser, GetCourse... I suppose that the other methods work...

There is one single small modification of the one posted above compared with this one
- around line 390 the method <message name="get_userRequest"> uses 4 parameters instead of 3 as this file contains ( <part name="idfield" type="xsd:string" /> is added)
- also, the methods are called "mdl_XXX" instead on just "XXX"

Catalin
In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Catalin Maican -
ok... so I found a temporary solution to my problem:

- /ws/lib/nusoap.php from mdl_soapserver.class.php - DOES NOT WORK FOR ME in VS 2005 - I get "method 'mdl_soapserverlogin' not defined in service" although it works in soapUI tool

The following library / moodle default / previous WS version ??? works in both VS 2005 and soapUI tool with Moodle 1.6

if (file_exists($CFG->libdir . '/nusoap/nusoap.php')) {
require_once($CFG->libdir . '/nusoap/nusoap.php');
} else if (file_exists($CFG->libdir . '/soap/nusoap.php')) {
require_once($CFG->libdir . '/soap/nusoap.php');
} else {
error('No SOAP library found!');
}

What should I do?

Catalin

In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Thanks Catalin for the wsdl.php for version 1.6

Unfortunatly I have only 1.7 and I tried with SoapUI tool and it is giving the error (Wed Apr 18 13:10:50 EDT 2007:WARN:Error: http://kdt-us-ssevern2/moodle1/ws/wsdl.php:0: error: soaparray: Invalid SOAP Array reference: xsd:string (prefix declaration not found or incorrect format)). After that it created methods. when I open login request I don't see input parameters. All I am seeing is this
 
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://kdt-us-ssevern2/moodle1/ws/wsdl">
   <soapenv:Header/>
   <soapenv:Body>
      <wsdl:login soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
   </soapenv:Body>
</soapenv:Envelope>

--------------

I tried the wsdl.php (the first file you posted at 6:19 pm) for 1.8 version and it didn't give me the error at SoapUI tool and the request for login is

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://kdt-us-ssevern2/moodle18/ws/wsdl">
   <soapenv:Header/>
   <soapenv:Body>
      <wsdl:mdl_soapserver.login soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <username xsi:type="xsd:string">?</username>
         <password xsi:type="xsd:string">?</password>
      </wsdl:mdl_soapserver.login>
   </soapenv:Body>
</soapenv:Envelope>

But it doesn't give any SOAP response.

In your case you said from SoapUI tool it is working, did you get xml response?

I will try to modify the mdl_soapserver class like you said and let you know.

In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Hi Catalin

I have modified the mdl_soapserver.class.php, still I am getting "Operation 'mdl_soapserverlogin' is not defined in the WSDL for this service" in VS 2005, but SoapUI didn't give the error but no output.

I found one more webservice testing tool is called LISA (http://www.itko.com/site/lisa/)  and it returns this following error for Login operation.

----------------

ERROR  - Exception:
ERROR  - Cannot convert form 2 to String
WARN   -  Call/Ctor com.itko.lisa.wsgen.mlogin.LoginReturn mdl_soapserverLogin( java.lang.String username, java.lang.String password ) exception is org.xml.sax.SAXParseException: Premature end of file.
INFO   - xception: Premature end of file.
--------------

I hope somebody can comeup with the answer.

Thanks for your support.

-Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Catalin Maican -
Hi,

I forgot to mention that I have also modified some definitions within mdl_soapserver.class.php as before: replaced "string[]" with "string" where an Array of type string was not required.

I attached my working solution.

I did try this solution for Moodle 1.8 but it does not work. I believe that server.class.php creates and uses some tables in the DB. My Moodle 1.8 is installed on SQL Server 2005 with ODBC (only this I could it get working) and, from what I can see/understand in this file (because my PHP skills are null), it checks for the DB type before creating the tables... so... I didn't have the possibility to check and try further on this version.

Also, check server.class.php from Patrick's post above.

Catalin
Average of ratings: Useful (1)
In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -
Catalin, is the attached web service folder for 1.6 or 1.8?
In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Catalin Maican -
only for Moodle 1.6

Catalin
In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Thanks Catalin it is working. I just tried login and it is working. I am going to try more operations.

-Mahesh

In reply to Catalin Maican

Re: OKTech Web Services (Updated again)

by Justin Filip -
Catalin,

Thanks for this. I'll start using the branches in the new Contrib to properly setup this code for specific versions of Moodle so that the 1.7 and higher code will be using the roles system and the XMLDB functionality (which will get your tables created in MSSQL).

I've downloaded all the files everyone has been posting lately and I think I might have to get my hands on a copy of VS 2005 just so I can test all this myself because so far my verification that it's working is to make sure my PHP test script still works.

Anyway, I'll get on that and post a new message as soon as I've got all the changes submitted so far worked in and when the version-specific code branches are setup as well.
In reply to Justin Filip

Re: OKTech Web Services (Updated again)

by Mahesh Thoppae -

Hi, I have a question in "edit_user" operation. I have successfully added user into the system. But the problem is the password saved without encoding format and where as moodle system created passwords are encoded. So it leads to login issue for users added from web services.

Is there any method to encode the password when we create users from webservices?

In reply to Mahesh Thoppae

Re: OKTech Web Services (Updated again)

by Justin Filip -
Well the Moodle password field in the database is just an MD5 hashed value of the plaintext password. Using 'edit_user()' to create a new user record is expecting the password to be supplied in this encoded MD5 form.
Average of ratings: Useful (1)
In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Justin Filip -
Thanks to the feedback and testing of everyone here I've gone through the code and implemented the following changes:
- tested to verify that the code works in Moodle 1.8
- added code to use roles & capabilities functionality if running on Moodle 1.7 or later
- upgraded the database upgrade functionality to use the XMLDB system (if available: Moodle 1.7 and higher)
- cleaned up WSDL and tested for successful import into Visual Studio 2005 by myself (thanks, Mahesh for the link to the free .NET trial software)

The VS2005 testing was adding the WSDL as a reference successfully and also using the commandline wsdl.exe command to verify that there were no errors or warnings output from the processing. I didn't actually try to write any clients which used this but if someone creates some code to test it from within VS 2005, please feel free to send it to me (I'll include it in the Contrib source). smile

Once again, just to make sure you've gotten the latest version of the code, the /ws/ directory now has a /db/ sub-directory containing /db/install.xml and the CVS ID tag in /ws/wsdl.php is:

$Id: wsdl.php,v 1.4 2007/04/24 04:05:36 jfilip Exp $
In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Patrick Pollet -
Hello,

Thanks for this new version ( $Id: wsdl.php,v 1.4 2007/04/24 04:05:36 jfilip Exp $).
But I have to confirm that it still does not work with php5 clients with built-in SoapClient nor python clients . Troubles comes from the naming convention of operation with a dot such as mdl_soapserver.get_course ... the wsdl files are parsed OK (execpt with wsdl2php or wsdl2java) but method calls fail ...


Tests with PHP 5 :
----------------------
$moodle= new SoapClient("http://cipcnet.insa-lyon.fr/moodle/ws/wsdl.php");

$types=$moodle->__getTypes ();
print_r($types);
$funcs=$moodle->__getFunctions ();
print_r($funcs);
$lr= $moodle->login("xxxx","zzzzz");
$lr= $moodle->mdl_soapserver.login("xxxx","zzzzz");
$lr= $moodle->mdl_soapserver__login("xxxx","zzzzz");
print_r($lr);

that gives a correct parsing of wsdl file
Array
(
[0] => struct userRecord {
string error;
integer id;
integer confirmed;
integer policyagreed;
integer deleted;
string username;
string password;
string idnumber;
string firstname;
string lastname;
string email;
string icq;
string skype;
string yahoo;
string aim;
string msn;
string phone1;
string phone2;
string institution;
string department;
string address;
string city;
string country;
string lang;
integer timezone;
string lastip;
string description;
}
[1] => userRecord userRecords[]
....
[snip]

Array
(
[0] => loginReturn mdl_soapserver.login(string $username, string $password)
[1] => boolean mdl_soapserver.logout(integer $client, string $sesskey)
[2] => editUserOutput mdl_soapserver.edit_user(integer $client, string $sesskey, editUserInput $users)
[3] => getUserReturn mdl_soapserver.get_user(integer $client, string $sesskey, getUserInput $userids, string $idfield)
[4] => editCourseOutput mdl_soapserver.edit_course(integer $client, string $sesskey, editCourseInput $courses)
[5] => getCourseReturn mdl_soapserver.get_course(integer $client, string $sesskey, getCourseInput $courseids, string $idfield)
[6] => getGradesReturn mdl_soapserver.get_grades(integer $client, string $sesskey, string $userid, getGradesInput $courseids, string $idfield)
[7] => enrolStudentsReturn mdl_soapserver.enrol_students(integer $client, string $sesskey, string $courseid, enrolStudentsInput $userids, string $idfield)
)


but a fatal error when calling login with any syntax (login, mdl_soapserver.login or mdl_soapserver__login "à la nusoap"):

PHP Fatal error: Uncaught SoapFault exception: [Client] Function ("login") is not a valid method for this service in /var/www/html/moodle172/ws/pp1.php:9
Stack trace:
#0 [internal function]: SoapClient->__call('login', Array)
#1 /var/www/html/moodle172/ws/pp1.php(9): SoapClient->login('xxxx', 'zzzzz')
#2 {main}
thrown in /var/www/html/moodle172/ws/pp1.php on line 9


Tests with wsdl2php:
------------------------
wsdl2php http://cipcnet/moodle/ws/wsdl.php

PHP Fatal error: Uncaught exception 'Exception' with message 'Invalid function call: loginReturn mdl_soapserver.login(string $username, string $password)' in /usr/share/pear/wsdl2php.php:128
Stack trace:
#0 {main}
thrown in /usr/share/pear/wsdl2php.php on line 128

wsdl2php refuses the dot in the name of function


Tests with python :
----------------------
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import SOAPpy

proxy = SOAPpy.WSDL.Proxy('http://cipcnet.insa-lyon.fr/moodle/ws/wsdl.php')
proxy.show_methods()


...
Method Name: mdl_soapserver.get_course

In #0: client ((u'http://www.w3.org/2001/XMLSchema', u'integer'))
In #1: sesskey ((u'http://www.w3.org/2001/XMLSchema', u'string'))
In #2: courseids ((u'http://cipcnet.insa-lyon.fr/moodle/ws/wsdl', u'getCourseInput'))
In #3: idfield ((u'http://www.w3.org/2001/XMLSchema', u'string'))
Out #0: return ((u'http://cipcnet.insa-lyon.fr/moodle/ws/wsdl', u'getCourseReturn'))
...

>>> a,b=proxy.login('xxxx','zzzzzz')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/opt/Plone-2.5/Python-2.4.3/lib/python2.4/site-packages/SOAPpy/WSDL.py", line 96, in __getattr__
if not self.methods.has_key(name): raise AttributeError, name
AttributeError: login

>>> a,b=proxy.mdl_soapserver.login('xxxx','zzzzzz')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/opt/Plone-2.5/Python-2.4.3/lib/python2.4/site-packages/SOAPpy/WSDL.py", line 96, in __getattr__
if not self.methods.has_key(name): raise AttributeError, name
AttributeError: mdl_soapserver
>>>
In reply to Patrick Pollet

TO DO

by Patrick Pollet -
Re,
In line 335 of server.class.php
(" . time() . " - s.sessionbegin) < " . $this->sessiontimeout . ";";

the semi-colon must be removed to avoid php warnings (at least with Moodle 1.7) that add a "with limit (-1,1)" at the end of the sql query when using record_exists_sql($sql).

[Tue Apr 24 13:37:12 2007] [error] [client 127.0.0.1] SQL You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; LIMIT 1' at line 6 in /var/www/html/moodle172/lib/dmllib.php on line 289. STATEMENT: SELECT s.*\n FROM mdl_webservices_sessions s\n WHERE s.userid = 2 AND\n s.verified = 1 AND\n s.sessionend != 0 AND\n (1177414632 - s.sessionbegin) < 1800; with limits (-1, 1)

HTH

In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Mahesh Thoppae -

Justin. Thanks for the new version. Where I can download the new version.

-Mahesh

In reply to Mahesh Thoppae

Re: OKTech Web Services (Another update)

by Justin Filip -
Mahesh,

Same URL as always: http://download.moodle.org/download.php/patches/ws.zip

That will always allow you to download the latest code from the Contrib CVS (without having to use CVS access directly).
In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Mahesh Thoppae -

Still I am getting 1.3 version downloadsad

In reply to Mahesh Thoppae

Re: OKTech Web Services (Another update)

by Mahesh Thoppae -

Thanks Justin for  1.4 version.

It is not giving any error when I add the wsdl into VS 2005. But when I try the login method it is giving error(Object reference not set to an instance of an object). My assumption is, it is not returning as object. Here is response from new version in 1.8 using SoapUI testing tool.

<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:si="http://soapinterop.org/xsd">
   <SOAP-ENV:Body>
      <mdl_soapserver.loginResponse xmlns="http://kdt-us-ssevern2/moodle18/ws/wsdl">
         <return>
            <client xmlns="">7</client>
            <sessionkey xmlns="">58c4353df662e6f76a09541b843aa078</sessionkey>
         </return>
      </mdl_soapserver.loginResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

---------------------------------

Response from Catalin posted webservice with 1.6.5 version and it is working one.

<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://kdt-us-ssevern2/ws/wsdl">
   <SOAP-ENV:Body>
      <ns1:mdl_soapserver.loginResponse xmlns:ns1="http://kdt-us-ssevern2/ws/wsdl">
         <return xsi:type="tns:loginReturn">
            <client xsi:type="xsd:integer">18</client>
            <sessionkey xsi:type="xsd:string">849c7c8f464831086b30864e7fa216e6</sessionkey>
         </return>
      </ns1:mdl_soapserver.loginResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

----------------------------------------

The main difference is, the response doesn't have the loginReturn object  (return tag) in the latest version and also datatype for client and sessionkey is not there.

In reply to Mahesh Thoppae

Re: OKTech Web Services (Another update)

by Justin Filip -
So mine is returning the correct data but it's not typed?

Hmm... I think it's time to drop NuSOAP for the server and write it using PHP5's built-in SOAP classes.

I imagine a lot of this garbage is all related to using NuSOAP.

And maybe get rid of the object-oriented structure because that seems to be causing problems (see Patrick's post above) even if they're not readily evident all the time.
In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Patrick Pollet -
I guess I can help since I have a running version with PHP5 as the only SOAP server but clients in other open source languages wink
(php5, php4 with NuSoap, python and java) .

Problem is that PHP5 is not yet required for Moodle ; this has been announced for 1.9, so we will break Moodles running on hosted servers still running php4...

I need few days to clean up my code and merge your changes for compatibility with Moodle 1.6 and higher...

Stay tuned .



In reply to Patrick Pollet

trouble with version 1.4

by Patrick Pollet -
Hello,

With the new version of the wsdl I have trouble with python clients (and in php5 client code with code generated with wsdl2php) due to the change of declaration of get_user (and get_course) parameters

In version 1.3 they were array of string,

// old

<xsd:complexType name="getUserInput">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType"
wsdl:arrayType="xsd:string[]" />
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>

and where sent by php4 nusoap client :
/// GET_USER
if (in_array('get_user', $tests)) {
print_heading('Get User:');
$userids = array();
if ($uids = explode(',', WS_USER_GET_IDS)) {
foreach ($uids as $uid) {
$userids[] = $uid;
}
}
proc_result($proxy->mdl_soapserver__get_user($mycid, $mykey, $userids, WS_USER_IDFIELD), $proxy);
}
and received and processed as an array by mdl_soapserver :
if ($users = parent::get_user($client, $sesskey, $userids, $idfield)) {

PHP5 server, clients and python clients were happy with it ...


In the new version they are now a sequence
//new
<xsd:complexType name="getUserInput">
<xsd:sequence>
<xsd:element name="userid" type="xsd:string"
minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>

sent in ws-test.php (with nusoap client) by :

/// GET_USER
if (in_array('get_user', $tests)) {
print_heading('Get User:');
$userids = array();
if ($uids = explode(',', WS_USER_GET_IDS)) {
foreach ($uids as $uid) {
$userids['userid'][] = $uid;
}
}
proc_result($proxy->mdl_soapserver__get_user($mycid, $mykey, $userids, WS_USER_IDFIELD), $proxy);
}

and still received & processed OK as an array of array by php4 nusoap server :
if ($users = parent::get_user($client, $sesskey, $userids['userid'], $idfield)) {


Unfortunately, with PHP5 SoapServer, and PHP5 or Python clients, the sequence is sent/received as a StdClass (normal since they are no array definition in the type) as it should be :

stdClass Object
(
[userid] => Array
(
[0] => user1
[1] => user2
)

)

and mdl_soapserver chokes on the line :


if ($users = parent::get_user($client, $sesskey, $userids['userid'], $idfield)) {

with the error :
PHP Fatal error: Uncaught SoapFault exception: [SOAP-ENV:Server] Cannot use object of type stdClass as array in /var/www/html/moodle172/ws/pp/MoodleWS.php:189


So my questions are :

- Were these change dictated by some VS 2005 specificities ?

- in that case we are in trouble because Python and Java clients cannot easily convert classes or dictionnaries to StdClasses expected by PHP.

- Can we provide TWO get_user/get_course/get_whatever calls, one named get_xxxx that accept ONLY one id as a string and return one xxxx record (these work here ) and another one "get_xxxxs" (plural name) that will accept (one day) an array of ids and will return an array of xxxx records ? Additional bonus could be that is the array of ids is empty, we could return all xxxx...

- To have a different name for the key of the returned array is a pain ; sometimes it is $res['users'], or $res['courses'] and here $res['categories'], $res['events'] ,$res['roles'] ... Could we have only $res['items'] or even $res[] ?


- I feel bad about returning passwords in get_user(s) calls. Some smart guys could use the Web service to fetch user(s) and try to reverse crack their md5 passwords with a dictionnary ...

Cheers


In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Catalin Maican -
hi,

I have a question related to the OO structure of the code used for the WS: if you "get rid" of this, what are the consequences related to the use of the WSDL in other platforms/clients ?

Thanks,
Catalin
In reply to Catalin Maican

Re: OKTech Web Services (Another update)

by Catalin Maican -
ok...

so I had some time to test the new version with ASP.NET... I only tried the login and GetUser methods and they work only with the following modifications:

- replaced "literal" with "encoded" in the mdl_soapserver.class.php and wsdl.php (soap:body use="encoded")
- replaced the NuSOAP library with the one included in Moodle

Also, this latest version only works with Moodle 1.6... (it does not create any new tables in the SQL Server 2005)

If I do not replace the nusoap, I get the following message:

System.Web.Services.Protocols.SoapException: Operation 'mdl_soapserverlogin' is not defined in the WSDL for this service
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at WindowsApplication1.ws4.MoodleWS.mdl_soapserverlogin(String username, String password) in E:\temp1\WindowsApplication1\WindowsApplication1\Web References\ws4\Reference.cs:line 121
at WindowsApplication1.Form1.button1_Click(Object sender, EventArgs e) in E:\temp1\WindowsApplication1\WindowsApplication1\Form1.cs:line 79

The attached WS is working now with a WindowsForms/C# client...
In reply to Catalin Maican

Re: OKTech Web Services (Another update)

by Justin Filip -
Did you have the latest code? Correct versions and everything? I know there's been some issues with anonymous CVS recently and I think that might've affected the download service.

If you have the latest code it *should* create tables in SQL server. It's using the XMLDB functionality to create the database tables (if you're using 1.7 or higher) so if you can actually install Moodle and have it running on SQL Server, then this should work also.

And I can't get the WSDL to be accepted in Visual Studio 2005 (either using the GUI tools to add a reference or using the wsdl.exe file on the command-line) unless use="literal".

I don't know what (if any) specific language it's attached to although I'm pretty sure it's *something .NET.

Can you supply me with the project files you're using in Visual Studio to try and get this working?
In reply to Justin Filip

Re: OKTech Web Services (Another update)

by Catalin Maican -
hi,

the version I used is 1.4, as you can see in my other post.

I attached here the WindowsForms project I used for testing the WS. The WS proxy/refrence needs to be named "ws4" or else you need to change the entire code.

Regarding the WSDL for the creation of proxy: I can attach it (add web reference -> url to the wsdl.php file) using both "literal" and "encoded", but when I use the "literal" there seem to be some errors/miss-types in the types for the generated proxy: some objects get to be of type XML and not of the correct type specified in the WSDL.

Regarding the SQL Server, I will try to create the tables manually and run the code again...

Catalin
In reply to Catalin Maican

Re: OKTech Web Services (Another update)

by Mahesh Thoppae -

Thanks Catalin. The one ws attachment you posted is working with moodle 1.8 version. Like you said, I commented out the nusoup came with the Webservices and uncommented the other one in the attachment.

Justin one more request, right now I can add users in to Moodle 1.8 system. But I would like to add users in LDAP authentication. There is no authentication field in userrecord or userdatum object. Can you please add this feature into Web services.

Thanks,

Mahesh

In reply to Mahesh Thoppae

Let' s give a try to v 1.5 ;-)

by Patrick Pollet -
Hello ,

At last here come something usable and slightly documented ... and since I am going away for a week, it is time to expose it ...

Server is PHP 5 only. It requires installation of php_soap extension.

Clients can be PHP4 with Moodle's provided nusoap library, PH5 with builtin SoapClient , Python or Java. See the directory "clients " for sample codes. I do not have around any Windows system to test VS access ...

This version provides 35 services that fulfill all my needs and are used here to sync Moodle with a Plone/Zope portal (Python), an ESup portal (Java/Tomcat) and PHP written systems (C2I testing platform).

WSDL is available (as before) from http://yourmoodle/wspp/wsdl_pp.php .

See the list below and the file client/supported_operation_list.txt for names and required parameters.


Method Name: login
Method Name: logout
Method Name: get_my_id
Method Name: get_courses
Method Name: get_course
Method Name: get_course_byid
Method Name: get_course_byidnumber
Method Name: get_courses_bycategory
Method Name: get_my_courses
Method Name: get_user
Method Name: get_users
Method Name: get_user_byusername
Method Name: get_user_byid
Method Name: get_user_byidnumber
Method Name: get_users_bycourse
Method Name: get_teachers
Method Name: get_students
Method Name: get_groups_bycourse
Method Name: get_group_members
Method Name: get_my_groups
Method Name: get_my_group
Method Name: get_group_byid
Method Name: get_groups_byname
Method Name: get_roles
Method Name: get_role_byname
Method Name: get_role_byid
Method Name: get_categories
Method Name: get_category_byid
Method Name: get_category_byname
Method Name: get_grades
Method Name: get_last_changes
Method Name: get_events
Method Name: edit_courses
Method Name: edit_users
Method Name: enrol_students


I kept most on the names invented by Justin, except that I added a plural (s) in case of possible multiple returns (eg get_courses , get_users, ...) . These operations accept an empty array of identifiers and then return all users, courses ... There are also some get_user_xxxx and get_course_xxxx operations that should return one single record, but still packed in an array.

All get_* operations and enrol_students have been fully tested under Moodle 1.7 but I did not gave a spin to edit_* operations that are inchanged from Justin's code.

I started to peek into Moodle 1.8 and noticed that with the new mnet, all Moodle cores API will be exposed to remote calls using XML-RPC. See this discussion http://moodle.org/mod/forum/discuss.php?d=68794

So it may make our efforts to improve our SOAP solution quickly obsolete ;-((

TODO:
- finish get_events to filter by course events, group events, global events ...
- the validate_client method is present but not called. So a session never expires .
...


Enjoy.

In reply to Patrick Pollet

Re: Let' s give a try to v 1.5 ;-)

by Catalin Maican -
Hi Patrick,

I was not able to use you version of WS with Visual Studio 2005

I have tried it on both Moodle 1.8 and 1.6, both on Win2003 with a WindowsForms/C# client.

Visual Studio created the proxy successfully but I cannot instantiate it / I can not find the class in the autocompleter...

in browser, the URL http://..../wspp/service_pp.php?type=soap gives me the following error (it has PHP5 and SOAP installed)

<?xml version="1.0" encoding="UTF-8" ?>
- <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
- <SOAP-ENV:Body>
- <SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Bad Request. Can't find HTTP_RAW_POST_DATA</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Also, in the wsdl_pp.php file, the "/ws/wsdl" should be replaced with "wspp/wsdl"

Catalin
In reply to Catalin Maican

Re: Let' s give a try to v 1.5 ;-)

by Patrick Pollet -
Catalin,

It is a pity that VS 2005 does not seem to comply with open standard . I really would like to see v 1.5 .NET compatible, but as I stated above, I do not have ( and do not want) to use/install proprietary software to ensure compatibility. I prefer to focus on adding more API operations or fix the current ones. Especially if the current efforts of the Moodle team to expose the API by XML-RPC become operational and well documented...

As far as the http://..../wspp/service_pp.php?type=soap error, no surprise. This was a NuSoap server only feature to allow a quite nice Web Browsing of types & operations. This is not implemented in PHP5 SoapServer class. The PHP5 built-in SoapServer expects SOAP data as HTTP_RAW_POST_DATA and complains if you call it with ?type=soap that arrive to it as HTTP_GET_DATA.

Do you think that VS use this call to fetch the list of operations ? Surprising ? It should read & parse the WSDL file and not an HTML document full of CSS directives .

What happens when you point a browser to http://yourmoodle/wspp/wsdl_pp.php ?
It should return yo a file named moodlews.wsdl for downloading . Can VS 2005 be happy by opening a local copy of this file instead of fetching it by a Web access ?

I also noticed that in the current version of wsdl_pp.php, some operations are declared with soap:body use="encoded" and some others as "literal". Some copy&paste that I did not checked. It does not make any harm here with my python & php clients ... I also tried ( with success) to have them all as "literal" or all as "encoded". VS seems to be a bit more restrictive ?

Last, it was my understanding that the namespace declaration ="'. $CFG->wwwroot . '/wspp/wsdl" was only a declaration and do not have to match the actual path to the server. Here it does not make any difference by using http://mymoodle/ws/wsdl or http://mymoodle/wspp/wsdl . I just wanted to keep the original namespace used by Justin.


Well, I really would like to help, but I just don't know how I can force proprietary software to comply with standard ...





In reply to Patrick Pollet

one further test

by Patrick Pollet -
Hello again,

I just tried the WSDL validator at http://xmethods.net/ve2/Tools.po against version 1.5 installed on my prod server and it indeed validate my WSDL and properly display the 35 operations with correct input & output types ...

So I just don't know what to do to help .NET clients.

In reply to Patrick Pollet

Is that do any good ?

by Patrick Pollet -
Hello again,

When testing my wsdl_pp.php against Java clients, I got a complain by WSLD2Java utility (not catched by other clients PHP4, PHP5 and python and also not by Xmethod validator ) that "changeRecords" type was used by not defined ... mort

Indeed it was missing ! Does the attached version of wsdl_pp.php do any good to VS 2005 ?

For information I succeeded in Java, using Apache Axis 1.4 to login and retrieve roles from my Moodle 1.7 prod server grand souriregrand sourire

Here my the test code :


/*
creating the WSDL
java -cp ./axis.jar:./commons-logging-1.0.4.jar:./commons-discovery-0.2.jar:./saaj.jar:./wsdl4j-1.5.1.jar:./jaxrpc.jar org.apache.axis.wsdl.WSDL2Java http://cipcnet/moodle/wspp/wsdl_pp.php


Compilation :
javac -cp ./axis.jar:./jaxrpc.jar:. Test1.java

Execution :
java -cp ./axis.jar:./commons-logging-1.0.4.jar:./commons-discovery-0.2.jar:saaj.jar::wsdl4j-1.5.1.jar:./jaxrpc.jar:. Test1

Output :
LR.client:563
LR.key:87e30dee8e308f1ab3c57cde26d0d986
ID=2
6 roles
1 Administrator
2 Course creator
3 Teacher
6 Guest
5 Student
4 Non-editing teacher
true

*/

// adjust the import to your Moodle wsdl package created by WSDL2Java !!!
import fr.insa_lyon.cipcnet.moodle.wspp.wsdl.*;

import org.apache.axis.AxisFault;

public class Test1 {


public static void main (String[] args) {

MoodleWSLocator service= new MoodleWSLocator();
try {

MoodleWSPortType port=service.getMoodleWSPort();

LoginReturn lr=port.login ("XXXXX","ZZZZZZ");
System.out.println ("LR.client:"+lr.getClient());
System.out.println ("LR.key:"+lr.getSessionkey());

System.out.println ( "ID="+
port.get_my_id(lr.getClient(),
lr.getSessionkey())
);


GetRolesReturn grr=port.get_roles(lr.getClient(),
lr.getSessionkey());

RoleRecord[] rr=grr.getRoles();
System.out.println(rr.length+" roles");

for (int i=0; i< rr.length;i++)
System.out.println (
rr[i].getError()+" "+rr[i].getId()+" "+rr[i].getName()

);


System.out.println (port.logout(lr.getClient(),lr.getSessionkey()));

}
catch (AxisFault af) {
System.out.println ("axis fault "+af);
}

catch (Exception e) {
System.out.println ("exception "+e);
}

}

}

In reply to Patrick Pollet

Re: one further test

by Catalin Maican -
Patrick,

The wsdl.exe tool gave me a clue:

- Unable to import operation 'get_last_changes'
- The datatype 'http://xxxxxxx/wspp/wsdl:changeRecords is missing...

http://support.microsoft.com/kb/820122

so, in wsdl_pp.php , the type "changeRecords" (~line 513) is not defined earlier as a complexType...Now, if I add a it as as complexType, by hand, in the WSDL, everything seems to be OK in VS2005, meaning that it generates the proxy.

Also, please replace, if possible, from soap:body use="literal" to soap:body use="encoded"...

For now, the login, get_users and get_courses methods in my test application work just fine...

Thanks,
Catalin



In reply to Catalin Maican

Fantastic ...

by Patrick Pollet -
So we did it !!!!!!!!!!!!!!!!! Our two messages crossed each other.

I think I have changed "literal" to "encoded" in the wsdl_pp.php attached to my message just above (that talk about java client and the missing changeRecords that I also catched when using WSDL2java )

Cheers .

NB: Best regards to all people of Brashov University that I have met in some past Tempus projects : Doru Ursutiu , Cornell Samoia and Radu (the computer man at the top of the tower to whom I showed Linux in 2001). Europe is really small wink))


In reply to Patrick Pollet

Revision 1.5.1

by Patrick Pollet -
Hello ,

I have bundled all above changes to revision 1.5.1, few improvments (filtering of events...) plus a major security fix if Moodle authentication method is set to some external method (CAS ...) .

Since version 1.5 seems to gain interest from others, I have started a page with latest versions, documentation, sample clients, TO DOs ... at

http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/

Enjoy.

NB: Justin , still around ? We fork ?

In reply to Patrick Pollet

Re: Error on 1.5.1

by Mahesh Thoppae -

Hi Patrick,

Thanks for your time to put in the new version. I tried the login method in VS 2005 and it is giving error,

SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://kdt-us-ssevern2/moodle18/wspp/wsdl_pp.php'
So I tried the SoapUI testing tool it gave me the same error when I try Login request.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>WSDL</faultcode>
         <faultstring>SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://kdt-us-ssevern2/moodle18/wspp/wsdl_pp.php'</faultstring>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Am I missing something?
Catalin, is the latest one works for you?
Thanks guys for your contribution.
In reply to Mahesh Thoppae

Re: Error on 1.5.1

by Catalin Maican -
Mahesh,

did you run the following command (specified in step 1 in Readme.txt)

php wsdl2php.php http://yourmoodle/wspp/wsdl_pp.php
?

if you run this command, it will replace (generate new files - classes for proxy) from the WSDL specified as parameter. I think that MoodleWS.php is used by the web service and this needs to be generated again with the correct URI for the calls. (or, at least, change the URI from that file to the correct address for your WS)

Hope this is helps (it works this way for me - both VS and soapUI)

Catalin
In reply to Catalin Maican

Re: Error on 1.5.1 Oups

by Patrick Pollet -
Hello,

Catalin is right ; You MUST run that command to adjust the URI in MoodleWS.php from my server to yours. MoodleWS.php is indeed used by the web service and the version included in 1.5.1 points to my server and not localhost like it was in 1.5.

I should find a way to force the MoodleWS.php file to be "autogenerated" at first run. Wait for 1.5.2 wink


My fault triste
In reply to Patrick Pollet

Re: Error on 1.5.1 A second thought

by Patrick Pollet -
Catalin and Malesh ,

I had a second thought to my post above and I think I was wrong.

The server code includes MoodleWs.php just a convenient way to have all classes associated to data types handy in one single requires. But the server's code does not instanciate the class MoodleWS (that extends SoapClient) included in that file , so even if the URI are wrong in the methods of MoodleWS, it should not matter.

A a test, I made a MoodleWS.php with only the requires directives at the top and removed all the code of the MoodleWS class. My clients are still happy ...


So I maintain my text in readme.txt that wsdl2php utility must be run on the client side ; but to me server should be up and running out of the box ...

Malesh,

There must be something else wrong in your setup.

The error SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://kdt-us-ssevern2/moodle18/wspp/wsdl_pp.php may indicate that soapUI could not reach your server or the directory wspp/ is not in moodle18 ?

BTW , if I copy & paste your URL in a browser, I get a "server not found page" ?

Have a nice week-end.

In reply to Patrick Pollet

Re: Error on 1.5.1 A second thought

by Mahesh Thoppae -

Patrick,

The server is inside firewall, so you can't reach it.

You said, wsdl2php needs to run on client side? is that mean I need to have php installed on client system?

I tried wsdl2php at server side but it gave me error.

C:\moodle\moodle\moodle\moodle18\wspp>php wsdl2php.php http://kdt-us-ssevern2/mo
odle18/wspp/wsdl_pp.php
PHP Notice:  Use of undefined constant PACKAGE - assumed 'PACKAGE' in C:\moodle\
moodle\moodle\moodle18\wspp\wsdl2php.php on line 33
PHP Notice:  Use of undefined constant AUTHOR - assumed 'AUTHOR' in C:\moodle\mo
odle\moodle\moodle18\wspp\wsdl2php.php on line 34
PHP Notice:  Use of undefined constant COPYRIGHT - assumed 'COPYRIGHT' in C:\moo
dle\moodle\moodle\moodle18\wspp\wsdl2php.php on line 35
PHP Fatal error:  Class 'SoapClient' not found in C:\moodle\moodle\moodle\moodle
18\wspp\wsdl2php.php on line 46

I have enabled Soapclient and phpinfo said soap is enabled.

Waiting for your suggestion.

Thanks

In reply to Mahesh Thoppae

1.5.2 is working!!!

by Mahesh Thoppae -

Patrick,

I have downloaded new version 1.5.2 from the url that you posted few days back, and it is working with SoapUI test tool and VS 2005 also. 

I didn't do any changes from your code and I have used only login operation. So far it looks good. Doing more testing.

Thanks Patrick and Catalin for all your help.smile

In reply to Mahesh Thoppae

Re: Error on 1.5.1 A second thought

by Patrick Pollet -
Mahesh,

A real strange error. The PHP warnings seem to indicate that wsdl2php.php was corrupted in some way. So no surprise, calling it from VS 2005 or soapUI will fail.

I double checked and the three DEFINES (PACKAGE, AUTHOR and COPYRIGHT) are at the top of the source code in v 1.5.1. ?

Anyway, this is history, since running wsdl2php.php is not anymore required at the server side, unless you plan to add more functions to the Web Service. It was indented that way starting at v 1.5.0, but obviously something was wrong.

wsdl2php.php is required on the client side ONLY if you are planning to write PHP5 clients; this make writing clients very easy ... otherwise it is absolutely not needed.

With Java clients I use WDSL2java and with Python, wsdl2py.

I shall try to get some english teacher here to proof read my READMEs that are sometimes not very clear ;-(


I am glad v 1.5.2 did the job.

v 1.5.3 is under the hood ; nothing new for you. I just added support for PHP5 clients without the extension php_soap, by using the old nusoap library, an (hopefully ) clearer README and some more Python examples with the ZIS library.



Cheers.


In reply to Patrick Pollet

Re: Revision 1.5.1

by Justin Filip -
Hi Patrick,

Yes, I'm still around. I was gone from Friday to Monday and spent all day yesterday catching up on things that I had missed while gone.

I'm going to go through what you've got here and get it into the contrib CVS so anyone downloading the code there can get access to it.

Thanks for your work on this.
In reply to Justin Filip

Re: Revision 1.5.1

by Patrick Pollet -
Hi Justin,

We are in June, and still nothing in the CVS ? Something wrong with my implementation ?

A lot of people are downloading it from my site (http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews)
and asking me why it is not in the contrib CVS ? May be in a "branch" ...

Sample codes are now available from Plone/Zope (python) , Java and php ... My version is now used in Plones prod servers.

Cheers.


In reply to Patrick Pollet

Re: Revision 1.5.1

by Justin Filip -
Hi Patrick,

The code is great.

Actually... do you have write access to the contrib CVS area for Moodle? If not you should get access for it because you've done a lot of work on this and much spent much more time than I've had avialable for this lately so, if you want to become the maintainer of the code in CVS, that's fine by me.

If you don't already have write access, send Martin D. a message on Moodle.org asking for it. You need to give him your Sourceforge username (you'll need one of those, as well, if you don't have one already).

Sorry, I've kind of forgotten about all this recently. If you wanted to backup what I had in CVS into a sub-directory or something go ahead or you can just overwrite what's there with your current code without saving mine (it would still be available because, well, it's in CVS).

In reply to Justin Filip

Re: OKTech Web Services

by Maram Meccawy -
Hi,
I'm about to upgrade to the new version of moodle: 1.8.1 for the reason of web services, which I need to use of integration purposes with an external..web service oriented system.
When I have extracted the new moodle I have noticed that the WS folder is mnet which appears to be a bit different than your package code. Are they really two different things? which one should I be using?


Thanx
In reply to Maram Meccawy

Re: OKTech Web Services

by Mike Churchward -
Picture of Core developers Picture of Plugin developers Picture of Testers
Yes, they are different animals...

'mnet' is the web services code created to handle the new 'Moodle networks' functions. You can still get our 'ws' from the 'contrib' repository.

I'm not sure how much cross-over there is between the two, but I would check them out and use which one makes sense for your application.

mike
In reply to Justin Filip

Re: OKTech Web Services

by Maram Meccawy -

Hi Justin,

I want to ask if it is possible to get the login information the other way round.

I need to integrate a system in which is a set of services into moodle, hence I need to be able to get the current loged user information from moodle so that it is passed from there to the other services in order for them to perform their tasks before returning the results to moodel (security is not an issue at the moment).

I would really appriciate it if you can give me some advise here on how is the best way to do it.

Cheers,

Maram

In reply to Maram Meccawy

Re: OKTech Web Services

by Patrick Pollet -
Hello Maram,

If I understand well your problem, you want to write some php code on the Moodle side, that will get current user data, connects to some Web service somewhere, fetch whatever relevant data and display it in Moodle ?

Here is a "sample code"... for some reason syntax highlighting for php does not seems to work anymore here ? You just have to replace my call to Moodle Web Services by a call to yours using code very similar to wspp/clients/MoodleWS.php .



// This script MUST be in a subdirectory of your Moodle Web site
// ie /var/www/html/moodle/tests

// get Moodle stuff
require_once("../config.php");
// must be logged in from another page in another window/tab else die
require_login();

// standard header using current theme
print_header( 'My Page Title','My Page Title','My Page Title');

print_simple_box_start("center", "100%", "", 5, "generalbox", "mypage");

print("Hello, world!");


// get current user info
$user=get_record('user',username,$USER->username);
//dump it to browser
print_r ($user);


// call Moodle WS for current user
require_once("../wspp/clients/MoodleWS.php");
require_once("../wspp/clients/auth.php");
$moodle= new MoodleWS();

//connect to Moodle WS using power user login/pwd
// we cannot use current user since his password is md5 encrypted ...
$lr= $moodle->login(LOGIN,PASSWORD);
print_r($lr);
print "";
// get and print last activities of this guy in an ugly way ...
print_r($moodle->get_activities($lr->client,$lr->sessionkey,$USER->username,"username",'','',10));
print "";
// plz don't forget to logout
$moodle->logout($lr->client,$lr->sessionkey);
// end call MoodleWS

//end of page using current theme
print_simple_box_end("center");
print_footer();









In reply to Maram Meccawy

Re: OKTech Web Services

by Justin Filip -
Maram,

Are you talking about what Patrick discussed -- getting user information for all the users on the site -- or about getting information from the users who are currently logged into the system at that exact time?
In reply to Justin Filip

Re: OKTech Web Services

by Maram Meccawy -
Hi Justin,

Thanks for replying. Sorry for not answering your question earlier, I had some visitors.

Actually am addressing the latter. i.e " getting information from the users who are currently logged into the system at that exact time "

I want to be able to send information about user ( at least username, name, pw) from moodle to an external system (where the same user is registered there as well) that would then prepare the response (adaptive/personalized content) to this particular users and send the result back to moodle's database.

Thanks a lot,
Maram
In reply to Maram Meccawy

Re: OKTech Web Services

by Justin Filip -
Maram,

Moodle doesn't really track users that are logged in at the moment, however it does track the last time that a user accessed something in one of their courses. In Moodle 1.7 and later this information is stored in the `user_lastaccess` table. In earlier versions it's a field in the `user_students`table.

You could sort of get the information you wanted by looking at the largest timestamp value in this table for a user. With a window of time (say 5 - 10 minutes) you could consider any user who has at LEAST accessed something on the site within that window of time as logged in, that would give you the results you want.
In reply to Justin Filip

WSDL Issue

by D T -
First, thanks to Justin & Patrick for all the work!

I have a problem with the WSDL file that is generated from my Moodle installation.

I have retrieved the file from <server>/moodle/wspp/wsdl_pp.php and copied it into my local Visual Studio 2005 project.
I then added it as a "web reference" and can successfully access all the web services except for the ones that reference "SOAP-ENC:Array" in their type definition. For example get_user_byid fails because the return type of getUsersReturn contains userRecords - which use the "SOAP-ENC:Array" type.

I am recieving the error in Visual Studio that "Imported schema for namespace 'http://schemas.xmlsoap.org/soap/encoding/' was not resolved", for the line: <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />.

The xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" attribute is present in the <wsdl:definitions> tag.

I wondered if anybody else had encountered (and hopefully resolved!!) the same problem.

Thanks in advance.


In reply to Justin Filip

Re: OKTech Web Services

by Ken DeVellis -

Hi Justin,

Thanks for your terrific work on the soap implementation of web services - I have successfully installed the WS in our 1.8.2 moodle and the soap functions work great! We use Visual Studio 2005 environment and C# for most of our development projects and are looking at integrating our .NET based SIS system we developed here with our moodle LMS.  Question: will all the WS v1.5.4 functions work with Moodle 1.9 and if not, will you be upgrading them?

Thanks again

In reply to Ken DeVellis

Re: OKTech Web Services

by Marko Novakovic -
Hi to all of you,

I have just found, how do i put it... "bug" in WS code... I was trying to extend some functionalities and i needed to include some of the moodle libraries in my functions..

I got error "cannot redeclare nusoap_base class" and i have found out that in some point, some of the moodle's files is including nusoap.php from lib/soap/ folder or something...

I just added checking if this moodle's nusoap exists and include either that file or that one with WS distribution.
In reply to Marko Novakovic

Re: OKTech Web Services

by Patrick Pollet -
Marko,

What version are you using ? the one from CVS (rev 1.4) which is really out of date or mine (rev 1.5.9) that is available only at cipcnet.insa-lyon.fr (see above) due to lack of answer of Martin D. for a CVS access ...
I suspect is it rev 1.4 since current version does not use at all nusoap on the server side .

In any case, you can submit me your patch for inclusion in the "main stream" .

Cheers.

In reply to Justin Filip

Re: OKTech Web Services

by Derek Wahila -
I just installed the latest wspp from Patrick -- http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/ -- 1.5.9

I am able to login, get_users, and logout. I cannot seem to format the call to add a user via edit_users.

Here's what I am doing (via PEAP_SOAP)...

[...]

$user_2 = new stdClass;
$user_2->action = 'Add';
$user_2->idnumber = 123;
$user_2->firstname = 'first';
$user_2->lasstname = 'last';
$user_2->username = 'username';
$user_2->password = 'password';
$user_2->email = 'email';

[...]

$results = $moodle->edit_users($client, $sesskey, Array('user'=>$user_2));

I get a response of...

[error] => no users

Pretty sure I just have the array of user object(s) incorrect.

Suggestions?

thanks,
-d
In reply to Derek Wahila

Re: OKTech Web Services

by Patrick Pollet -
Hello,
the user's data must be an array and must be send also as an hash with the key 'users' (note the plural) so :

$users=array();
$users[]=$user_2; // your user to add
$users[]=$another_one;
...

$results = $moodle->edit_users($client, $sesskey, array('users'=>$users));

also note a spelling error in $user_2->lasstname = 'last'; (must be lastname).

HTH



In reply to Patrick Pollet

Re: OKTech Web Services

by Catalin Maican -
Hello Patrick,

I've found that adding a user to a 1.8.3 installation, that user is not allowed to log in.

Apparently in the "mdl_user" table there is a field (mnethostid) that is not filled in ? At least in my installation, when changing that value from 0 to 1 in the database it worked ok.

Thanks,
Catalin
In reply to Patrick Pollet

Re: OKTech Web Services

by Derek Wahila -
Patrick, thanks. that was all I needed. Working like a charm, though I had the same problem that Catalin Maican mentioned (on Friday, 23 November 2007). Users added the the SOAP call could not log in. I added this to the user array:

$new_user->mnethostid = 1;

and they can log in now.

One more question:

I defined some user profile fields. Can I use the SOAP call to also fill in this data? I tried the obvious

$new_user->newfield = 'aaa';

but that didn't work. Is this possible with the current release? I have admittedly not looked at your source.

If it's not currently possible, could the server-side code be reasonably modified to support this (I can give it a whirl) if you think so...

thanks,
-d


In reply to Derek Wahila

Re: OKTech Web Services

by Patrick Pollet -
Hello,

I am glad it worked for you.
A much better "patch" would be to add in function edit_user of server_class.php after the line '$useradd = $user) :


$useradd = $user;

//Moodle 1.8 and later (a required field that must be non 0 for login )
if ($CFG->mnet_localhost_id)
if (!$useradd->mnethostid) //if not set by caller (TODO add to userdatum record)
$useradd->mnethostid = $CFG->mnet_localhost_id; // always local user



As far as your "extra fields" are concerned it would be a bit more difficult since you MUST ALSO add these field names to the WSDL sent by the wsdl_pp.php script at the end of the "userdatum" XML entry ; the names MUST match your names in your database
something like :

xsd:element name="extrafield1" type="xsd:string"
xsd:element name="extrafield2" type="xsd:string"
xsd:element name="extrafield3" type="xsd:string"


That should be enough for the server side to add your values to the SOAP data received from client, and inject them in the new user record in the database .

I shall be glad to hear about your testing in this direction.
Cheers

































...

In reply to Patrick Pollet

Re: OKTech Web Services

by Derek Wahila -
I've made the changes to the server.class.php -- which made perfect sense.

Then I modified the wsdl_pp.php as well.

What I don't understand, is where to make the additional db calls to write the other fields to the database. The user data is written using the insert_record function in dmllib.php

I know my optional fields need to go into the mdl_user_info_data table, using the fields that were written to the mdl_user_info_field table.

Since this is a single installation, and we are managing it, I know the additional fields will not change. That means I know the fieldid, and the userid and data will come from the WS add/edit.

But, like I said, I just don't know where to actually perform the db insert/edits. Being unfamiliar with the moodle code, any advice or pointers would be very helpful. And certainly appreciated.
In reply to Derek Wahila

Re: OKTech Web Services

by Patrick Pollet -
Hello Derek,

Taking in account the new optional fields introduced in Moodle 1.8 will be a big plus that I would like to support.

Your request would require a "big change" in the wsdl production since the "userDatum" record will have to be "dynamically generated" by reading the new tables (mdl_user_info_field and mdl_user_info_category) to adjust it to the site's extra fields.

Actually I am considering the idea on changing the wsdl_pp.php file (or at least its first part that deal with basic Moodle entities (user,course,grade..), to be fully dynamic by reading the current database structure. This should make migration of the Web Service much easier across Moodle new releases.. but will make life a bit more complex to people using wsdl2xx generators to produce their client's code ( Java, Python/ZIS ...) in static classes. They would have to regenerate their classes at every upgrade of Moodle ...

I am planning to install a Moodle 1.8.3+ during the winter vacations to see all problems introduced by this release... So give me some time wink


Season's greetings.



In reply to Patrick Pollet

Request for testing

by Patrick Pollet -
Hello,

It has been reported to me that with Python/ZSI clients, current version of the Web Service (1.5.9) raises a fatal error when returning an user data when its description field has no data. This is due to the fact that in mdl_user table, the field description is the only one with attribute "NULL" on ; all other optional fields (icq, skype ...) have attribute NULL unset and a default value as empty string. For some reason, ZSI consider that by default an attribute is never 'null' and raises a fatal error on user's description :

ZSI.EvaluateException: Non-nillable element is NIL

The solutions are quite simple :

  • change the NULL attribute of description field in mdl_user table from NULL to NOTNULL and default to '' , but this is a Moodle core change ...
  • or modify the script wsdl_pp.php to have in userRecord entry :
xsd:element name="description" type="xsd:string" nillable="true"

instead of

xsd:element name="description" type="xsd:string"

This simple patch may have to be repeated to other database fields that have also the NULL attribute set (very few indeed) ...

I am quite ready to release 1.5.10 with such a patch (and the mnethostid problem reported above by Catalin) , but I just want to make sure that all types of clients I am not testing will not choke on this. I am thinking to .NET/Visual Studio and Java/Axis.

So if some good souls using these can test that adding nillable="true" does not break their clients and report here of directly to me ...


Season's greetings.



In reply to Justin Filip

Re: OKTech Web Services

by Colin Chambers -
Hi guys,

I'm a little confused now that Moodle Network is available I see that it can offer web services too. I think this might have been asked elsewhere but I can't find the post.

What is the future for Web Services in Moodle. Are these Web services part of core. Are you guys doing the web services and Moodle Network doing the community hub? YOu've got a soap solution and Moodle Network has XML RPC would you consider merging so that you can support both ina standard fashion.

I'm not trying to rain on your parade I'm just using web services for a solution I'm developing and so the questions are really pertinent.

Cheers
In reply to Colin Chambers

Re: OKTech Web Services

by Patrick Pollet -
Hello,

As discussed in another topic, http://moodle.org/mod/forum/discuss.php?d=82322
the SOAP and XML-RPC are two different approaches.

My understanding is that Moodle NetWork has a much more general approach on exporting Moodle internal API, but still lack of "concrete entry points" via XML-RPC to get/set/delete/modify Moodle entities such as students, courses ,grades ...
In the contrary, the SOAP approach has some these entry points, but will be more difficult to maintain with the high speed Moodle version changes.

Definitivly merging will be profitable, but this would require :
- more documentation on the "developper side" of Moodle Network layer.
- a complete rewriting of the SOAP internal layer (as implemented in our server.class.php).
- an agreement on the desired entry points. A beginning is on   http://docs.moodle.org/en/Development:Web_services a page initiated by Martin D., but currently only "filled in" by me ...

Also I still do not have CVS access to the OKTech branch in Moodle's contrib area, so you should consider the SOAP approach as an non officially supported initiative. I does work, with Moodle
In reply to Patrick Pollet

Re: OKTech Web Services

by Colin Chambers -
Thanks for that reply patrick I appreciate such a quick response. That makes things much clearer.
In reply to Patrick Pollet

Re: OKTech Web Services

by Catalin Maican -
Patrick,

The MoodleWS implementation supports Login and Logout operations. Can they be used to login (and logout) an user for creating a SSO application ? e.g. if I login automatically an user via "login" operation from the Web Services, will he/she need to login again ?

Thanks,
Catalin
In reply to Catalin Maican

Re: OKTech Web Services

by Catalin Maican -
Hi, again,

maybe I was not clear enough in my latest post, so I would like to ask the same with other words: is it possible to create an authentication plugin so that when an user is authenticated via the Login method in web services, he/she would also be authenticated in Moodle (the user not being asked to enter the user/pass again in browser ?)

Thanks,
Catalin
In reply to Catalin Maican

Re: OKTech Web Services

by Steven House -

Hello,

I am really needing to get something working in C# using the service, do I have the latest version with 1.5.9? I have tried your sample applications and it cant find a method or 2, so Im thinking I have an old version. I feel I am close, but I seem to be getting this error:

System.InvalidOperationException: Client found response content type of 'text/html', but expected 'text/xml

The request failed with an empty response.
   at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   at WindowsApplication1.LuxorLMS.MoodleWS.login(String username, String password) in C:\JZA\E\iVersity\AI\MoodleWS\WindowsApplication1\Web References\LuxorLMS\Reference.cs:line 297
   at WindowsApplication1.Form1.button1_Click(Object sender, EventArgs e) in C:\JZA\E\iVersity\AI\MoodleWS\WindowsApplication1\Form1.cs:line 79

In reply to Steven House

Re: OKTech Web Services

by Patrick Pollet -
Hello,

1.5.9 is the latest released. I have many others projects running and do not intent to release anything until the official Web Service API for Moodle is more advanced .

Your error message (System.InvalidOperationException: Client found response content type of 'text/html', but expected 'text/xml) seems to indicate that the Web server has not returned an XML answer (a Soap answer) but some error message (page not found, authentification failed, acces denied ...)

Try to call the Web service from a Browser to see what can be the problem ...

http://youmoodlebaseurl/wspp/service_pp.php

You should get in French the list of supported functions :

Ce serveur SOAP peut gérer les fonctions suivantes : mdl_soapserver blank_array error_record to_soap to_soap_array edit_users get_users edit_courses get_courses get_grades enrol_students error get_user get_groups get_my_courses get_my_courses_byusername get_my_courses_byidnumber get_user_byusername
....

I suspect you will get some other error message

Cheers.
In reply to Patrick Pollet

Re: OKTech Web Services

by Rafael Ferreira -
Guys,

Is there a reason why the wsdl is set to RPC/encoded as opposed to rpc/literal? I'm getting errors while trying use wsdl2java on the generated wsdl (rpc/encoded is not supported by neither axis nor xfire)

rafael-mb:bin rafael$ ./wsdl2java.sh -o /tmp -p com.uvasoftware.judo.moodle.ws -uri file:/Users/rafael/Downloads/moodlews.wsdl
Using AXIS2_HOME: /Users/rafael/dev/java/axis2-1.3
Using JAVA_HOME: /usr
[ERROR] Encoded use is not supported
org.apache.axis2.description.WSDL11ToAxisServiceBuilder$WSDLProcessingException: Encoded use is not supported
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.getPartsListFromSoapBody(WSDL11ToAxisServiceBuilder.java:1777)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.createSchemaForPorttype(WSDL11ToAxisServiceBuilder.java:1528)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.generateWrapperSchema(WSDL11ToAxisServiceBuilder.java:1431)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.populateService(WSDL11ToAxisServiceBuilder.java:255)
at org.apache.axis2.description.WSDL11ToAllAxisServicesBuilder.populateAllServices(WSDL11ToAllAxisServicesBuilder.java:109)
at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.(CodeGenerationEngine.java:141)
at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
at org.apache.axis2.wsdl.WSDL2Java.main(WSDL2Java.java:24)
...


In reply to Rafael Ferreira

Re: OKTech Web Services

by Patrick Pollet -
I suspect that you are not using the latest 1.5.9 version but the preliminary 1.4 version available on CVS.

see http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews

You will find reports of successful use with Java and Axis library.

Cheers.


In reply to Patrick Pollet

Re: OKTech Web Services

by Rafael Ferreira -
I was able to dig a little bit further into this and this is what I was able to find out.

* The WSDL as is will work on axis 1.x since it uses rpc/encoded
* The WSDL will not work with a modem java soap stack which is JAXWS2.0 compliant since they only work with document/literal AFAIK.

I was able to test this using Axis 1.4, axis2, Metro and XCF.

- raf
In reply to Rafael Ferreira

Re: OKTech Web Services

by Patrick Pollet -
Hello Raf,

Sorry for the delay.

It is quite unfortunate and I just don't know what to do ;-((

I installed axis2 rev 1.4 (latest) and I get almost right away another error (before your reported complain about Encoded not supported) ...

ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/bin$ sh wsdl2java.sh -uri http://mymoodle/wspp/wsdl_pp2.php
Using AXIS2_HOME: /home/ppollet/passage/tmp/moodle/ws/axis2-1.4
Using JAVA_HOME: /usr
Retrieving document at 'http://mymoodle/wspp/wsdl_pp2.php'.
Exception in thread "main" org.apache.axis2.wsdl.codegen.CodeGenerationException: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.generate(CodeGenerationEngine.java:271)
at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35)
at org.apache.axis2.wsdl.WSDL2Java.main(WSDL2Java.java:24)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at org.apache.axis2.wsdl.codegen.extension.SimpleDBExtension.engage(SimpleDBExtension.java:53)
at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.generate(CodeGenerationEngine.java:224)
... 2 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.axis2.wsdl.codegen.extension.SimpleDBExtension.engage(SimpleDBExtension.java:50)
... 3 more
Caused by: org.apache.axis2.schema.SchemaCompilationException: can not find type {http://schemas.xmlsoap.org/soap/encoding/}Array from the parent schema http://mymoodle/wspp/wsdl
at org.apache.axis2.schema.SchemaCompiler.copyMetaInfoHierarchy(SchemaCompiler.java:1296)
at org.apache.axis2.schema.SchemaCompiler.processComplexContent(SchemaCompiler.java:1258)
at org.apache.axis2.schema.SchemaCompiler.processContentModel(SchemaCompiler.java:1153)
at org.apache.axis2.schema.SchemaCompiler.processComplexType(SchemaCompiler.java:1097)
at org.apache.axis2.schema.SchemaCompiler.processNamedComplexSchemaType(SchemaCompiler.java:1017)
at org.apache.axis2.schema.SchemaCompiler.processSchema(SchemaCompiler.java:931)
at org.apache.axis2.schema.SchemaCompiler.processElement(SchemaCompiler.java:592)
at org.apache.axis2.schema.SchemaCompiler.processElement(SchemaCompiler.java:552)
at org.apache.axis2.schema.SchemaCompiler.process(SchemaCompiler.java:1991)
at org.apache.axis2.schema.SchemaCompiler.processParticle(SchemaCompiler.java:1880)
at org.apache.axis2.schema.SchemaCompiler.processComplexType(SchemaCompiler.java:1081)
at org.apache.axis2.schema.SchemaCompiler.processNamedComplexSchemaType(SchemaCompiler.java:1017)
at org.apache.axis2.schema.SchemaCompiler.processSchema(SchemaCompiler.java:931)
at org.apache.axis2.schema.SchemaCompiler.processElement(SchemaCompiler.java:592)
at org.apache.axis2.schema.SchemaCompiler.processElement(SchemaCompiler.java:552)
at org.apache.axis2.schema.SchemaCompiler.process(SchemaCompiler.java:1991)
at org.apache.axis2.schema.SchemaCompiler.processParticle(SchemaCompiler.java:1874)
at org.apache.axis2.schema.SchemaCompiler.processComplexType(SchemaCompiler.java:1081)
at org.apache.axis2.schema.SchemaCompiler.processAnonymousComplexSchemaType(SchemaCompiler.java:980)
at org.apache.axis2.schema.SchemaCompiler.processSchema(SchemaCompiler.java:934)
at org.apache.axis2.schema.SchemaCompiler.processElement(SchemaCompiler.java:592)
at org.apache.axis2.schema.SchemaCompiler.processElement(SchemaCompiler.java:563)
at org.apache.axis2.schema.SchemaCompiler.compile(SchemaCompiler.java:370)
at org.apache.axis2.schema.SchemaCompiler.compile(SchemaCompiler.java:280)
at org.apache.axis2.schema.ExtensionUtility.invoke(ExtensionUtility.java:103)
... 8 more

Same error when changing use="encoded" to use="literal" in all operations entries in the wsdl.


wsdl2java seems to be chocking on the declaration of userRecords as an array of userRecord :


<xsd:complexType name="userRecords">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType"
wsdl:arrayType="tns:userRecord[]" />
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>







which is to my little knowledge the "standard way" ...

It just goes past my understanding ;-(

What surprise me the most is that the Java built soapUI interactive application seems to be pleased with current WSDL definitions .

In reply to Patrick Pollet

Re: OKTech Web Services

by Patrick Pollet -
Hello raf again,

With some help from a java guru, which I am not all all I succeeded in generating the classes from current WSDL by using the xmlbeans databinding, and not the abd Axis default .

Here is my output :


ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/bin$ sh ./wsdl2java.sh -uri http://cipcnet.insa-lyon.fr/moodle/wspp/wsdl_pp.php -o ../moodlews -d xmlbeans
Using AXIS2_HOME: /home/ppollet/passage/tmp/moodle/ws/axis2-1.4
Using JAVA_HOME: /usr
Retrieving document at 'http://cipcnet.insa-lyon.fr/moodle/wspp/wsdl_pp.php'.
[INFO] The ../moodlews/src/fr/insa_lyon/cipcnet/moodle/wspp/wsdl/MoodleWSCallbackHandler.java file cannot be overwritten.
[INFO] The ../moodlews/src/fr/insa_lyon/cipcnet/moodle/wspp/wsdl/MoodleWSStub.java file cannot be overwritten.
ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/bin$ cd ../moodlews/
ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/moodlews$ ant
Buildfile: build.xml

init:

jar.xbeans:
[jar] Building jar: /home/ppollet/passage/tmp/moodle/ws/axis2-1.4/moodlews/build/lib/XBeans-packaged.jar

pre.compile.test:
[echo] XmlBeans Availability = true
[echo] Stax Availability= true
[echo] Axis2 Availability= true

compile.src:
[javac] Compiling 464 source files to /home/ppollet/passage/tmp/moodle/ws/axis2-1.4/moodlews/build/classes
[javac] Note: Some input files use or override a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.

jar.client:
[jar] Building jar: /home/ppollet/passage/tmp/moodle/ws/axis2-1.4/moodlews/build/lib/MoodleWS-test-client.jar

BUILD SUCCESSFUL
Total time: 23 seconds
ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/moodlews$


Next step was to create a small java client in moodlews/src

import java.rmi.RemoteException;
import org.apache.axis2.AxisFault;

import fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub;

public class Test1 {

/**
* @param args
*/
public static void main(String[] args) {
MoodleWSStub stub =null;
try {

stub = new MoodleWSStub();
} catch (AxisFault e) { e.printStackTrace(); }

}
}

ant compile it OK, and place Test1.class in moodlews/build/classes, but I am unable to run it due to class not found errors ...

I keep on adding jars and so far I am stucck with this :
ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/moodlews/build/classes$ sh run.sh
.:./stax-api-1.0.jar:lib/wstx-asl-3.2.4.jar:lib/XmlSchema-1.4.2.jar:lib/activation-1.1.jar:lib/axiom-api-1.2.7.jar:lib/axiom-dom-1.2.7.jar:lib/axiom-impl-1.2.7.jar:lib/axis2-adb-1.4.jar:lib/axis2-kernel-1.4.jar:lib/commons-codec-1.3.jar:lib/commons-httpclient-3.1.jar:lib/commons-logging-1.1.1.jar:lib/stax-api-1.0.1.jar:lib/wsdl4j-1.6.2.jar:lib/xmlbeans-2.3.0.jar:lib/xml-apis-1.3.04.jar:lib/log4j-1.2.15.jar
Exception in thread "main" java.lang.NoClassDefFoundError: edu/emory/mathcs/backport/java/util/concurrent/ConcurrentHashMap
at org.apache.axis2.description.AxisDescription.(AxisDescription.java:78)
at org.apache.axis2.description.AxisService.(AxisService.java:363)
at org.apache.axis2.description.AxisService.(AxisService.java:434)
at fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub.populateAxisService(MoodleWSStub.java:41)
at fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub.(MoodleWSStub.java:580)
at fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub.(MoodleWSStub.java:569)
at fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub.(MoodleWSStub.java:617)
at fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub.(MoodleWSStub.java:609)
at Test1.main(Test1.java:15)
ppollet@prope:~/passage/tmp/moodle/ws/axis2-1.4/moodlews/build/classes$
In reply to Patrick Pollet

Finally OK with axis 2 ;-)

by Patrick Pollet -
This test class using axis2 did run against current WSDL in rpc/encoded and using
xmlbeans data bindings ... What a pain ;-((

Maybe some java guru around will contribute to help us on that ....


import java.rmi.RemoteException;
import org.apache.axis2.AxisFault;

// adjust to the package name created by wsdl2java.sh
import fr.insa_lyon.cipcnet.moodle.wspp.wsdl.MoodleWSStub;
import fr.insa_lyon.cipcnet.moodle.wspp.wsdl.*;

import java.math.BigInteger;

/*
to create the jars files
go to axis2 bin directory :

- sh ./wsdl2java.sh -uri http://cipcnet.insa-lyon.fr/moodle/wspp/wsdl_pp.php -o /tmp/moodlews -d xmlbeans
- cd /tmp/moodlews
- ant

add to your classpath
- all jars in axis2/lib (may be too much wink)
- PLUS the jar generated by ant in /tmp/moodlews/build/lib (MoodleWS-test-client.jar)

compile this and run

really less simple than with axis 1.4 !
I still don't know how to extract courses from the returned CourseRecords in XML ;-((

enjoy wink

*/



public class Test1 {

/**
* @param args
*/
public static void main(String[] args) {
MoodleWSStub stub =null;
try {
stub = new MoodleWSStub();
} catch (AxisFault e) {
e.printStackTrace();
}

LoginDocument loginDocument= LoginDocument.Factory.newInstance();
LoginDocument.Login loginDocumentLogin= loginDocument.addNewLogin();

loginDocumentLogin.setUsername("xxxxxx");
loginDocumentLogin.setPassword("xxxxx");
loginDocument.setLogin(loginDocumentLogin);
System.out.println(loginDocument);
try{
LoginResponseDocument rep=stub.login(loginDocument);
System.out.println(rep.getLoginResponse().getReturn());
// keep returned values to be sent at evry subsequent calls
BigInteger client =rep.getLoginResponse().getReturn().getClient();
String sesskey=rep.getLoginResponse().getReturn().getSessionkey();


GetMyCoursesDocument gmcd =GetMyCoursesDocument.Factory.newInstance();
GetMyCoursesDocument.GetMyCourses gmcd2= gmcd.addNewGetMyCourses();
gmcd2.setClient(client);
gmcd2.setSesskey(sesskey);

GetMyCoursesResponseDocument repgmc = stub.get_my_courses(gmcd);
CourseRecords myc =repgmc.getGetMyCoursesResponse().getReturn().getCourses();
System.out.println(myc); // still in XML !!!

LogoutDocument logoutDocument= LogoutDocument.Factory.newInstance();
LogoutDocument.Logout logoutDocumentLogout= logoutDocument.addNewLogout();
logoutDocumentLogout.setClient(client);
logoutDocumentLogout.setSesskey(sesskey);
LogoutResponseDocument rep2=stub.logout(logoutDocument);
System.out.println(rep2.getLogoutResponse().getReturn());


} catch (RemoteException e) { e.printStackTrace(); }


}
}
In reply to Patrick Pollet

Re: Finally OK with axis 2 ;-)

by abdelaziz ouadah -

Hello,

i am using this example test1.java to test access to the web service

my service end point is :http://127.0.0.1/wspp/service_pp.php

all the procedure work fine;

but when i try to run the example i have this exception:

<login xmlns="http://127.0.0.1/wspp/wsdl">

<username xmlns="">teacher</username>

<password xmlns="">test</password>

</login>

[INFO]

OMException in getSOAPBuilder

org.apache.axiom.om.OMException

at [row,col {unknown-source}]: [1,0]

at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(

at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.getSOAPEnvelope(

at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.<init>(

at org.apache.axis2.builder.BuilderUtil.getSOAPBuilder(

at org.apache.axis2.transport.TransportUtils.createDocumentElement(

at org.apache.axis2.transport.TransportUtils.createSOAPMessage(

at org.apache.axis2.transport.TransportUtils.createSOAPMessage(

at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(

at org.apache.axis2.description.OutInAxisOperationClient.send(

at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(

at org.apache.axis2.client.OperationClient.execute(

at _1._0._0._127.wspp.wsdl.MoodleWSStub.login(

at ws.context.Test1.main(

Caused by:

at [row,col {unknown-source}]: [1,0]

at com.ctc.wstx.sr.StreamScanner.throwUnexpectedEOF(

at com.ctc.wstx.sr.BasicStreamReader.handleEOF(

at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(

at com.ctc.wstx.sr.BasicStreamReader.next(

at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(

at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(

... 12 more

[INFO] Remaining input stream :[]

Any suggestion please ;

Thanx

: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prologStAXOMBuilder.java:249)StAXSOAPModelBuilder.java:156)StAXSOAPModelBuilder.java:105)BuilderUtil.java:677)TransportUtils.java:182)TransportUtils.java:112)TransportUtils.java:88)OutInAxisOperation.java:353)OutInAxisOperation.java:416)OutInAxisOperation.java:228)OperationClient.java:163)MoodleWSStub.java:1241)Test1.java:36)com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prologStreamScanner.java:661)BasicStreamReader.java:2134)BasicStreamReader.java:2040)BasicStreamReader.java:1069)StAXOMBuilder.java:506)StAXOMBuilder.java:161)
In reply to abdelaziz ouadah

Re: Finally OK with axis 2 ;-)

by Patrick Pollet -
Abdelaziz,

I see at least one mistake :
the end point should be
http://127.0.0.1/moodle/wspp/service_pp.php
(replace moodle by wathever folder name you used
in Moodle installation).

that is you must unzip the wspp_xxx.zip inside the Moodle directory, not elsewhere ... this may explain the UnexpectedEOF execption (no answer or internal error likely due to the first line of service_pp.php script (require_once('../config.php');) that fails with a file not found error...

Also some others developers had trouble with axis2. I had some success but I am not good enough in java to complete it
see http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/some-success-with-the-new-axis-2-library/


the provided Test1.java class has been succesfull with axis1.4. See comments atop this file to compile and run it.

In reply to Patrick Pollet

Re: Finally OK with axis 2 ;-)

by abdelaziz ouadah -

Thanx for your respone,

but when i call the  http://127.0.0.1/wspp/wsdl_pp.php , i have the wsdl file coorectly.

but the end point no response.

i tried the http://127.0.0.1/moodle/wspp/service_pp.php, but i have had 404 error page.

also   when i pull up http://127.0.0.1/wspp/service_pp.php in my browser and it's a blank page.

also i am using SOAPUI to test services, (with the same end point:http://127.0.0.1/wspp/service_pp.php). 

i sent the soap message:

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://127.0.0.1/wspp/wsdl">
   <soapenv:Header/>
   <soapenv:Body>
      <wsdl:login soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <username xsi:type="xsd:string">admin</username>
         <password xsi:type="xsd:string">test</password>
      </wsdl:login>
   </soapenv:Body>
</soapenv:Envelope>

and i have got this response:

HTTP/1.1 200 OK
Date: Tue, 27 Oct 2009 12:25:49 GMT
Server: Apache/2.2.8 (Win32) mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5
X-Powered-By: PHP/5.2.5
Set-Cookie: MoodleSession=7bc0688d791e8100ea1b1f1205a8bcfa; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: MoodleSessionTest=W6H1z8zKAW; path=/
Content-Length: 0
Content-Type: text/html

Thanx

In reply to abdelaziz ouadah

Re: Finally OK with axis 2 ;-)

by Patrick Pollet -
Abdelaziz,

>but when I call the http://127.0.0.1/wspp/wsdl_pp.php , i have the wsdl file coorectly.

Strange... and are you sure that your Moodle works correctly ? how do you call it
http://127.0.0.1/moodle ??? if so you call the Web Service by

http://127.0.0.1/moodle/wspp/wsdl_pp.php


You should NEVER call thee end point (service_pp.php) . This is sent to clients within the wsdl file...

So you MUST :

-unzip wspp_xxx.zip inside your moodle directory
or move the directory wspp inside it

- call http://yourmoodledirectory/wspp/wsdl_pp.php either in soapUI (via a New WSDL project) or in java

Cheers.
In reply to Patrick Pollet

Re: OKTech Web Services

by Josh Smith -
what would it mean when i pull up http://myclientmoodleurl/wspp/service_pp.php in my browser and it's a blank page?

I'm working with .NET and a client of our has moodle setup on his server. I'm trying to make some calls to it via the webservices. He has installed MoodleWS 1.5.9 over the weekend.

What could I ask my client to do (if anything) to fix this?

Thanks,

Josh
In reply to Josh Smith

Re: OKTech Web Services

by Patrick Pollet -
Josh,

Check in the Web server logs. I suspect some fatal php error has occured such as a missing library ( php_soap extension).

Alternatively check Info PHP at http://yourmoodle/admin/phpinfo.php and make sure that soap extension is loaded.

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by Josh Smith -
So you're saying in fact that I should get something when I pull up that page correct?

Directory browsing is enabled on my client's url and that file is listed like this:
service_pp.php 05-May-2007 06:30 947
It is very small. Is it supposed to be?

I'm having my client check on what you suggested above.

Thanks for the help.
In reply to Josh Smith

Re: OKTech Web Services

by Patrick Pollet -
Yes, You should get in French the list of supported functions :

Ce serveur SOAP peut gérer les fonctions suivantes : mdl_soapserver blank_array error_record to_soap to_soap_array edit_users get_users edit_courses get_courses get_grades enrol_students error get_user get_groups get_my_courses get_my_courses_byusername get_my_courses_byidnumber get_user_byusername
....

The script service_pp.php is the "dispatcher" for the Web service. If called by POST by any SOAP client, it perform the requested operation as per the WSDL and answer in XML, and if called by GET (from a browser without any parameter), it just tells you it is alive...

Small but beautiful wink

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by Josh Smith -
Thanks for the help Patrick.

I've successfully created a user! One thing though. I'm not able to login until I manually update the column mnethostid to 1 (in the mdl_user table). Any reason or way to fix that? There is no corresponding property (that I can tell) in the webservice.

This is basically the code I'm using:

/*
* Create a new user
*/
userData = new userDatum();
userData.firstname = "josh";
userData.lastname = "smith";
userData.city = "Raleigh";
userData.country = "US";
userData.username = "testuser";
userData.password = CalculateMD5Hash("password");
userData.email = "josh@email.com";
userData.action = "Add";
userData.confirmed = "1";

EditUsersIn = new editUsersInput();
EditUsersIn.users = new userDatum[] { userData };

EditUsersOut = m.edit_users(ret.client, ret.sessionkey, EditUsersIn);

if (EditUsersOut != null)
{
Console.WriteLine("User Created");

userRecord = EditUsersOut.users[0];

Console.WriteLine("id: " + userRecord.id);
Console.WriteLine("username: " + userRecord.username);
Console.WriteLine("confirmed: " + userRecord.confirmed);
Console.WriteLine("error: " + userRecord.error);
Console.WriteLine("role: " + userRecord.role);
Console.WriteLine("idnumber: " + userRecord.idnumber);
}


Also, do you know if there is any API or documentation for required fields, more explanation, etc? For instance userData.action = "Add". I can't even remember how I found it should be 'Add'. But any information would greatly help. I've got several other functions to implement.

Thanks in advance.
In reply to Josh Smith

Re: OKTech Web Services

by Mohammed Khan -
Hi,

I am currently using the wspp 1.5.9, along with moodle 1.9 . I am currently testing the services using soapui and would like to know how can i extend the web services in order to obtain the following using php :

1.get user roleid
2.get languages available in the system

Also when i t enrol more than one student to a course, and when try to run get_users_bycourses i get only one record (which was added last in the enrol array) i.e if i added user1, user2, user3 and when i run service get_users_bycourses i only get one record of user3.

Any help would be appreciated, and thanks in advance.
In reply to Mohammed Khan

Re: OKTech Web Services

by Patrick Pollet -
Hello Mohammed,

Sorry for the delay.


1) to get user role id ( in a course since an user can have different roles in different courses) you can call get_primaryrole_incourse and "fill the blanks " in soapUI as below with :

the client and sesskey returned by a previous login
the user's identifier (iduser) and the name of the field (iduserfield)
the course's identifier (idcourse) and the name of the field (idcoursefield) :


<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="http://cipcnet.insa-lyon.fr/moodle/wspp/wsdl">
<soapenv:Header/>
<soapenv:Body>
<wsdl:get_primaryrole_incourse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<client xsi:type="xsd:integer">21157</client>
<sesskey xsi:type="xsd:string">f16704fae413ec393a05cc74ae47ab55</sesskey>
<iduser xsi:type="xsd:string">vcottineau</iduser>
<iduserfield xsi:type="xsd:string">username</iduserfield>
<idcourse xsi:type="xsd:string">java_2eu_2008</idcourse>
<idcoursefield xsi:type="xsd:string">idnumber</idcoursefield>
</wsdl:get_primaryrole_incourse>
</soapenv:Body>
</soapenv:Envelope>

it should returns an integer matching the Moodle's standard roles ids :
1 admin
2 coursecreator
3 teacher
4 noneditingteacher
5 student
6 guest

<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://cipcnet.insa-lyon.fr/moodle/wspp/wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:get_primaryrole_incourseResponse>
<return xsi:type="xsd:integer">5</return>
</ns1:get_primaryrole_incourseResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

or an error is user's is unknown or not in the course :

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>user username='azerty' not found</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>



2) to get available languages, you will have to add yourself the required operation to the WSDL since it is not yet supported. See http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/how-to-extend-moodle-web-services/

3) I am surprised with this. enrol_students and get_users_bycourse are two different operations.
Did you checked in Moodle ( block participants) that user1,user2 and user3 where indeed added to the course ?
I never tested enrol_students with soapUI since I do not know how to fill the parameter with an array of student ids :

<userids xsi:type="wsdl:enrolStudentsInput" soapenc:arrayType="xsd:string[]"/>

but I did tested it in php and python ...

Cheers.


In reply to Patrick Pollet

Typo In Debug Line

by Terry Wickenden -

Minor Point but might be useful if you are debugging as I was. Line 519 of server.class.php has a typo - $userass instead of $useradd.

Threw me totally as a user had been added but no ID appeared in the Debug file

In reply to Terry Wickenden

Re: Typo In Debug Line

by Patrick Pollet -
I fell bad about this one...
I don't know what I was thinking about [blush]
I shall commit it to CVS asap ...

Thanks.
In reply to Patrick Pollet

Re: OKTech Web Services

by Mohammed Khan -
Hi Patrick,

Thanks for the help, i am now able to make soap request for getting languages and countries. But i am in a situation now, i am integrating moodle with a flex frontend, and using soap communication between moodle and flex ui, i am stuck at a point where i have to perform the following the operations form flex ui :

1) Upload scorm package
2) Upload users using CSV

As i am not very good in php i need scripts which can help me do this without any session or user authentication. Any help on this would be greatly appreciated and thanks for all you can do.
In reply to Justin Filip

Edit a course with java WS

by Igor Barma -
Hi,
I hope it's the good place to ask this kind of question....
I would like to modify moodle objects (courses, users) throw a SOAP call in java. For instant, I'm able to request courses list, users in a course, ....
But i want to modify a course (enrole a new student or a new teacher).
I try to do this but it's not working...

LoginReturn loginReturn = stub.login("xxxx", "yyyy");
...
/* I login and take a CourseRecord object to realize my test*/
myCourse = .........

EditCoursesInput editedCourses = new EditCoursesInput();

/* this method,
"getCourseDatumFromCourseRecord" create a CourseDatum object filled with all the given CourseRecord object values and set the action to "update" */
CourseDatum cD = getCourseDatumFromCourseRecord(myCourse);

cD.setFullname("Ohh ca marche");
CourseDatum[] coursesDatumArray = new CourseDatum[1];
coursesDatumArray[0] = cD;
editedCourses.setCourses(coursesDatumArray);
EditCoursesOutput returnCourses = stub.edit_courses(client, sesskey, editedCourses);
System.out.println(returnCourses.getCourses().length);
System.out.println( ((CourseRecord) returnCourses.getCourses()[0]).getFullname() );
System.out.println( ((CourseRecord) returnCourses.getCourses()[0]).getError() );


After that, my course is not edited...
Is anybody has ever done the same operation??
Or possible i didn't understood the way to use the WS...

Thanks for your help,
Igor

In reply to Igor Barma

Re: Edit a course with java WS

by Igor Barma -
Ohhh, sorry...
I post the previous message too quickly!!!
In fact i need to set the action value to "Add", "Update" or "Delete" with an uppercase...
Now, I have an error:
Could not update course: ID007

but it's better than nothing...


In reply to Igor Barma

Re: Edit a course with java WS

by Igor Barma -
OK, I found my problem.
When I re-send the moodle course object to update it, my description was filled with a ' char and there's no quote operation on it.
The SOAP request is ok and the WS server call the moodle lib update_record function as is.
So I had a SQL syntax error...
In reply to Justin Filip

Re: OKTech Web Services

by Renato Jr -
Hi,
I'm a newbie in WS, but I'm needing to use it for Moodle authentication.
This is how I need it to work:
1) The user will enter with his login and password on Moodle;
2) Moodle has to verify the information entered in another system (jsp);
3) If the data entered is correct, he has to be redirected to Moodle's index. If it's not, he has to go to the login page.

Does OKTech Web Services support this?

Another questions I have are related to storage of the user data:
4) Will it be stored on Moodle database?
5) If yes, do I always need to check if the data has been changed?
6) If not, how does it work?

Sorry for my poor english and thanks a lot for any help.
In reply to Renato Jr

Re: OKTech Web Services

by Patrick Pollet -
Hi Renato,

The Web Service do not deal with external authentification. Its main purpose is to export/import data from and to Moodle using an existing account , not to call an external Web Service. It is a WS server, not client...

I think you should turn yourself to this page on Moodle Docs
http://docs.moodle.org/en/Authentication

Cheers.
In reply to Patrick Pollet

Re: OKTech Web Services

by Renato Jr -
Patrick,

i really need to use WS authentication.
Today, i'm using the version 1.9.3+. I could see that version 2.0 includes WS authentications (http://docs.moodle.org/en/Development:Web_services#Authentication), but it expected mid-2009. So i have to create this auth's method, because i can't wait for the release version.

Thanks for your help.
In reply to Renato Jr

Re: OKTech Web Services

by Patrick Pollet -
Renato,

I think you misunderstood the term Web_services#Authentication in these pages.

We are talking about authentification of a WS client to Moodle as server (to secure the server part on Moodle and check for capabilities to perform import/export of data) and not the other way around.

Sorry.
In reply to Patrick Pollet

Re: OKTech Web Services

by Renato Jr -
Sorry, the mistake was mine.

Does it means that there is no development for user's authentication with WS? I thought there was..
Anyway, thanks for helping me.

Renato

In reply to Justin Filip

Re: OKTech Web Services

by Brian Mullaney -
I'm trying to get the web services package working on v1.9.4 of Moodle. Most things seem to be working correctly, but the get_grades method (which is critical for us) doesn't seem to work on 1.9.

There are a couple (at least 2) methods that get_grades() is calling (grade_get_preferences, grade_get_formatted_grades) aren't there. After some digging, I found that they exist in grade/lib.php in Moodle v1.8, but they're not there in 1.9.

Has anyone else experienced this? I tried doing some googling and searching of this forum and couldn't find anything. Is this method not supported in 1.9?
In reply to Brian Mullaney

Re: OKTech Web Services

by Hubert Chathi -
Moodle 1.9 introduced the gradebook, and so the API for getting grades has changed. Take a look at http://docs.moodle.org/en/Development:Grades to see how the gradebook can be used. It should be a simple matter to adapt the function to the new API according to your requirements.
In reply to Hubert Chathi

Re: OKTech Web Services

by Patrick Pollet -
Hello,

A modification to this Web Services was announced here (A Moodle-SIS Integration Project via Web services) http://moodle.org/mod/forum/discuss.php?d=102511 that includes among others things extraction of grades a la 1.9

I never had time to "merge" it with CVS since none of my servers having grades activated are running 1.9 ; they are still in 1.7 or 1.8 . The patch is for an old version off the Web Services but I think the grading part could be easily extracted and added to the current code

If I implements it do you want to be a tester for that ?


Cheers.

In reply to Justin Filip

wsdl2php ERROR

by Oscar Peli -

Hello Patrick,
I'm trying to add some methods but when I run wsdl2php I get the following error:

C:\moodle\server\php>php.exe ../moodle/wspp/wsdl2php.php http://localhost:8080/wspp/wsdl_pp.php/a>

Fatal error: Class 'SoapClient' not found in C:\moodle\server\moodle\wspp\wsdl2php.php on line 88

Soap is enabled as phpinfo tells me.

Any ideas?
Thanks.

Oscar

In reply to Oscar Peli

id vs. idfield

by easy rider -

I have a short question :

A primary key in the table mdl_user is id (with autoincrement), idfield is optional field. In the file server.class.php -> function edit_user(..) -> case 'Update' there is a couple of rows:

case 'Update':

 $userup = $user;
 $uid    = $userup->idnumber;

...

 $user = get_record('user', 'idnumber', $userup->idnumber);

...

You try to get user record by means of optional field idnumber. is that correct?

In reply to easy rider

Add new function in OkTech Web Service

by Sébastien Massat -
Hello,

I do not know if the question was already asked, but I would like create a new function in my OkTech webservice .
 
I'm working with moodle since 2 weeks and I want to create the function "edit_section" and "enrol_teacher" but I do not know what are the files in which implement these functions.

In addition I do not know php that since 1 month.

Thank you for your help
In reply to Sébastien Massat

Re: Add new function in OkTech Web Service

by Patrick Pollet -
In reply to Patrick Pollet

Re: Add new function in OkTech Web Service

by Frédéric Hoogstoel -
Hello,

some students at Polytech'Lille have integrated the web services developped at Lille ( http://www.assembla.com/wiki/show/MoodleWSPourGenDep ) in the web services developped at INSA Lyon ( http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/how-to-extend-moodle-web-services/ )

Where can I publish the results of this work ?

Cheers.
F. Hoogstoel
In reply to Frédéric Hoogstoel

Re: Add new function in OkTech Web Service

by Frédéric Hoogstoel -
In the meantime, you can get the results (code + documentation) of the students work at :
http://efidiles.plil.net/
In reply to Frédéric Hoogstoel

Re: Add new function in OkTech Web Service

by defus defus -
I can't access your Web page. Kaspersky display a Trojan-Clicker.JS.Agent.gk error.


In reply to defus defus

Re: Add new function in OkTech Web Service

by Sébastien Massat -

I have added some functionalities in Oktech WebService (add_sections, add_ressources, add_labels, assign_label_ressource_section, enrol_user_generics)

I will put my work in the community

Thanks for you help.

In reply to Sébastien Massat

Re: Add new function in OkTech Web Service

by Patrick Pollet -
Hello Sebastien,

Glad you have contributed. I shall release next week revision 1.6 where a great number of operations developped by PolyTech Lille will be added; Some of them seems to be also covered by your extension. I think we should synchronize their additions and your ..

see this discussion http://moodle.org/mod/forum/discuss.php?d=126195

Cheers.
In reply to defus defus

Re: Add new function in OkTech Web Service

by Patrick Pollet -
Yes the site http://efidiles.plil.net/moodle9/moodle/, which is not mine, has definitively be hacked . If you peek into source code (with a Linux based navigator not sensible to this trojan ), you shall see some hidden iFrames pointing to some sites in .ru domain !

I have contacted his maintainer ...
In reply to Patrick Pollet

Re: Add new function in OkTech Web Service

by Mahesh Thoppae -
Hi Patrick,

Great work on modifying and maintaining OKTech web services. Two years back I used your web services with VS 2005 and now I am trying to use more functions. I tried ver. 1.5.16, it works and looking for more. Are you planning to release new version (1.6) any time soon?

Thanks,
Mahesh
In reply to Justin Filip

Re: OKTech Web Services

by Wanderlei Junior -
Hello there,

I've just installed the the code dowloaded from "http://download.moodle.org/patches/ws.zip" and it appears to work. I can create courses, get users information. But...

When I try to enrol a student in a course using the method "enrol_students", it doesn't work. After we call this method, the user appears in the course's participant list, but Moodle keep asking for course's enrolment key.

Is that indeed the lastest version? (The file RELEASE.txt state it is version 1.5.5)

Any hints?

Thanks in advance,

Junior
In reply to Wanderlei Junior

Re: OKTech Web Services

by Mahesh Thoppae -
Hi Junior, here is the latest version link http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/

It works for me when I try to enrol a student. I am using VS 2008 C#.

-Mahesh
In reply to Mahesh Thoppae

Re: OKTech Web Services

by Wanderlei Junior -
Thank you Mahesh!

I think the issue was my Moodle installation. I've reinstalled it and the enrolment using the web service has worked!
Thank you for your reply, I will try to use this version.

Junior.
In reply to Wanderlei Junior

OK Tech Web Services : new release

by Patrick Pollet -
Hello ,

I am annoncing here the new release, tagged 1.6 today.
  • version 1.6 19/10/2009 download
    • Major rewriting
    • 104 functions calls and 76 custom datatypes see javadoc http://prope.insa-lyon.fr/~ppollet/moodlews/java/javadoc/ and espcially class MoodleWSBindingStub
      • Moodle 1.9.5 compatible
    • added operations by Lille team : thanks to Frédéric Hoogstoel, and his students : Amaury Rosart et Maxime Leu, en projet de 4ème année de formation d'ingénieur à Polytech'Lille, département IMA . Gabriela Fedor, Eduard Fidiles et Gabriel Tirnovan, étudiants roumains de l'université Stefan cel Mare de Suceava en stage
    • internationalization possible with an lang/xx_utf8_local/wspp.php file
    • returns dates in both unix time stamp and localized strings
    • moodle < 1.7 not anymore supported
    • change to get_grades to support new Moodle 1.9 gradebook
    • better support of roles & capabilities (filtering functions moved to filterlib.php)
    • support of groups and groupings
    • added add, delete and update_ operations that accept only one item (course, user,group, grouping...) instead of using the still supported edit___ operations that require an array of items, even if only one is to be processed.
    • removed all deprecated calls (isadmin(), isteacher() ....
    • session timeout and global access set in $CFG
    • usage of global $USER set properly in validate_client and used in capabilty checking
    • admin settings screen for basic configuration (see file admin/wspp.php for instructions)
    • log all operations in Moodle's log as per some CFG entries
    • removed all ob_* functions (managed globally at mdl_soapserver.class level)
    • better internal error output within xml stream (see mdl_sopaserver.class send method)
    • get_my_courses and get_users_bycourse now return the "primary role of requested user" (1 admin, 2 creator, 3 teacher ...)
    • entity identifier field added in all operations (except get_my_courses that still use Moodle internal id, see get_my_courses_byxxxx for other calls .
    • moved the wsdl code to an XML file, thus allowing easier extensions using a dedicated editor

Updated documentation is at the usual place. http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews

This revision will hit the Moodle's CVS in a few days.
Enjoy.

In reply to Patrick Pollet

Re: OK Tech Web Services : new release

by Michal Hruby -
Hi,
i'm trying to set up the 1.6 moodleWS, but i got this error and i have no clue how to resolve this issue.
X:\SOFT\xampp\htdocs\wspp\clients>X:\SOFT\xampp\php\php.exe ../wsdl2php.php http://localhost/wspp/wsdl_pp.php
SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://localhost/wspp/wsdl_pp.php' : Premature end of data in tag definitions line 2 in X:\SOFT\xampp\htdocs\wspp\wsdl2php.php:88
Stack trace:
#0 X:\SOFT\xampp\htdocs\wspp\wsdl2php.php(88): SoapClient->SoapClient('http://localhos...')
#1 {main}

I can run
php wsdl2php.php moodlewsdl.xml successfully, but when i try to run some test client i got similar error as above and SoupUI also doesnt work.

Thx for advice.
In reply to Michal Hruby

Re: OK Tech Web Services : new release

by Patrick Pollet -
Michal,

The wspp directory (the server part) MUST be at the first level of your Moodle installation. So your must unzip it inside it and the correct URL should likely be :
http://localhost/moodle/wspp/wsdl_pp.php

To use wsdl2php.php, just copy it anywhere else (not in the xamp/htdocs) or on another machine. see http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/wsdl2php/

Just replace 'moodle' by the real name of that directory in case your installed it elsewhere

Cheers.
In reply to Patrick Pollet

Re: OK Tech Web Services : new release

by Michal Hruby -
Patrick,
I'm now running moodle under ubuntu. I followed all steps in your readme. All is working but when i want to try some test clients (ppdemo,test_login and so on) I got this error:
I was trying all what i had on my mind but nothing helpsmile

Fatal error: Uncaught SoapFault exception: [SOAP-ENV:Server] [[ws_accessrestricted]] in /var/www/moodle/wspp/clients/MoodleWS.php:368 Stack trace: #0 /var/www/moodle/wspp/clients/MoodleWS.php(368): SoapClient->__soapCall('login', Array, Array) #1 /var/www/moodle/wspp/clients/tests/test_login.php(11): MoodleWS->login('jozko', 'jozko') #2 {main} thrown in /var/www/moodle/wspp/clients/MoodleWS.php on line 368

BTW: I dont exactly understand why there is duplicite clients and servers files in wspp directory? Why we call MoodleWS.php in clients directory instead of that in the server directory?

Sorry for my dump questionssmile
Thx much.



In reply to Michal Hruby

Re: OK Tech Web Services : new release

by Patrick Pollet -
Michal,

By default Version 1.6 blocks access (err [ [ws_accessrestricted] ] ) .

You have two solutions :

1) install the "admin settings " part see comment atop file wspp/admin/wspp.php by adding
the line

require("$CFG->dirroot/wspp/admin/wspp.php");

inside the file moodle/admin/settings/misc.php just before this line
// hidden scripts linked from elsewhere

Then go to Administration of your site and you should find a new Folder OK Tech Web services under the misc folder... there you can unckeck the option ws_enforceipcheck, and play with other options.

2) better, keep it checked and add using phpmyadmin the ip addresses of authorized clients in the table mdl_webservices_clients_allow
at least one record with ip=127.0.0.1 and maybe another one with the real ip address of the machine having the client part.

I also notice that the err string in between [ [ ] ], that mean that you forgot to copy the language file wspp/lang/fr_utf8/wspp.php into you moodledata/lang/xx_utf8 or better into a folder named moodledata/lang/xx_utf8_local , so it won't be destroyed by future languages packs Moodle upgrades. (replace xx with your country code)

Good luck

Edit : I take note of removing this security setting in forthcoming v 1.6.1, that has an auth plugin specific for Web Services, thus avoiding to disclose an admin login/password to developpers of external information systems.

BTW : forget pp_demo_*.php scripts and use test scripts in clients/tests directory (cleaner and simpler)

For you second question, you will notice that files MoodleWS.php in wspp and in wspp/clients are different in size.
The first one in only a long serie of requires for the server part and should not be changed (unless you modify the webservice, see script wspp/mkclasses.sh) .

The second one has also all the methods needed by the clients and is generated by the wsdl2php utility to match the real address of you Moodle site. I put it into the clients directory as samples, but normally this should be removed from production server and should be regenerated on "real client machines" (see again wspp/clients/mkclasses.sh).

Finally , your questions are not dumb, it is my documentation that is poor wink
In reply to Patrick Pollet

Re: OK Tech Web Services : new release

by Patrick Pollet -
hello again,

Please find attached the missing INSTALL file that will be released with rev 1.6.1 in few days..

Comments and corrections are welcome wink

Cheers
In reply to Patrick Pollet

Re: OK Tech Web Services : new release

by Razvan Musca -
Hello can anyone help me regarding this api, how can i use the add_user command?

this is the sample i have:

userDatum userData = new userDatum();
userData.username = username;
userData.auth = "manual";
userData.firstname = firstName;
userData.lastname = lastName;
userData.confirmed = "1";
userData.email = emailAddress;
userData.policyagreed = "1";
userData.passwordmd5 = pwdMD5;
MoodleWService.add_user("0", "", userData);

i am getting error "Invalid client connection".

Any help would do a lot!
In reply to Justin Filip

Use OKTech Web Services en .NET (C#)

by Alonso Uribe -
Me descargue las librerias OKTech y la uso en .NET y todo va muy bien pero aun no entiendo la estructura. Me gustaria que me ayudarán con lo siguiente:

Quiero que mediante .NET pueda hacer login como profesor y me regrese los cursos que tiene y luego los alumnos que tiene en el curso.

Si tienen alguna aplicación de ejemplo, les agradeceria bastante.

Les adjunto para que descarguen mi aplicación.

Moodle and .NET
http://www.megaupload.com/?d=J69DVWO0

Saludos.

PD: lo subi en megaupload porque solo se permite 100kb.


In reply to Alonso Uribe

Re: Use OKTech Web Services en .NET (C#)

by Paul Charsley -

Hola Alonso,

El proyecto Lightwork (http://lightwork.massey.ac.nz) ocupa las librerias OKTech para hacer lo que usted quiere hacer. Se puede conseguir el codigo en el archivo lightwork-*-moodle.zip en http://lightwork.massey.ac.nz/projects/list_files/fat. Los web services se encuentran en moodle/local/lightwork/ws/.

Si tiene alguna pregunta, se puede agregarla en la pagina forums.

Saludos,

Paul 

In reply to Paul Charsley

Re: Use OKTech Web Services en .NET (C#)

by Alonso Uribe -
Muchas gracias por contestar @Paul Charsley pero no pude publicar los WS de Lightwork.

Donde puedo encontrar ejercicios para integrar los WS con .NET, se lo agradeceria mucho.

Hasta luego.

Saludos.
In reply to Paul Charsley

Re: Use OKTech Web Services en .NET (C#)

by Alonso Uribe -
@Paul Charsley sigo interesado en el tema.

Espero pronto su respuesta, gracias.

Saludos.
In reply to Paul Charsley

Re: Use OKTech Web Services en .NET (C#)

by Alonso Uribe -
Cómo puedo aprender usar los servicios web de OKTech Web Services utilizando .NET?.

No encontré algun manual, me podrían ayudar.

saludos.


In reply to Justin Filip

Re: OKTech Web Services

by Elliot Rapp -
Ok, I think I have installed and configured everything correctly. However, when I try to run the test script /wspp/clients/tests/test_get_roles.php I get the following error:

Fatal error: Uncaught SoapFault exception: [SOAP-ENV:Server] web service access not allowed for your ip address xx.143.8.234. in /web/sites/commonwealth.xx.net/html/magento/moodle/wspp/clients/MoodleWS.php:378 Stack trace: #0 /web/sites/commonwealth.xx.net/html/magento/moodle/wspp/clients/MoodleWS.php(378): SoapClient->__call('login', Array, Array) #1 /web/sites/commonwealth.xx.net/html/magento/moodle/wspp/clients/tests/test_get_roles.php(12): MoodleWS->login('admin', 'xx') #2 {main} thrown in /web/sites/commonwealth.xx.net/html/magento/moodle/wspp/clients/MoodleWS.php on line 378

Note that I replaced some items with 'xx' just to retain that air of mystery wink

I can see the wsdl, the login credentials for MoodleWS->login are my admin credentials which I know work fine. Also, I have ws_enforceipcheck unchecked in the admin under webservices.

Any ideas?

Thanks!
In reply to Justin Filip

Problems install OKTech Web Services in moodle19

by Jorge Fierro -
Hi buddies,
My problem is this, I would like to help me with the installation and
configuration of the module OKTech Web Services (ws.zip), unzipped it and agregre in "moodle19/mod/ws", then we will try to activate it in the Link "Notifications", but when you clip gives me the following error "Module" WAS "is Not readable - check permissions."
In advance we thank you for the help they can provide.
In reply to Jorge Fierro

Re: Problems install OKTech Web Services in moodle19

by Dean Stringer -
Greetings Jorge. The OKTech solution is not a module so does not go into your /mod/ folder. You need to re-read the installation instructions, looks like you can read them here..

http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews
In reply to Dean Stringer

Problems with enrol_students

by Elliot Rapp -
Ok, I am struggling with enrol_students. I have moodle set up and working and am able to get some of other other test calls to work correctly (add_user for example).
However, I can't get enrol_students or get_users_bycourse to work correctly.

For enrol_students I am confused by these parameters:
* @param string $courseid
* @param string $courseidfield
* @param (enrolStudentsInput) array of string $userids
* @param string $useridfield

Is the array supposed the integer id's for those users (i.e. '3') or is it supposed to be their username (i.e. "bobsmith")? Also, what are the courseidfield and useridfield supposed to be?

Sorry, I don't see any explanations and am also trying to get this hooked up to Magento. I'm looking through the db and trying every combination, but so far no luck.

Thanks,
Elliot
In reply to Elliot Rapp

Re: Problems with enrol_students

by Elliot Rapp -
Ok. I got it to work.

This always happens. Figure it out ten minutes after you post on the forum.
In reply to Elliot Rapp

Re: Problems with enrol_students

by Patrick Pollet -
Hi,

In every call to the web service the field xxxxidfield , if present, states what db field you want to use to identify the target entity xxxx (says course, user, group....). If absent it is implied that the entity will be identified by its Moodle internal id ( group, groupings, activities...).

When you plan to 'update Moodle', It should be the name of an unique field such as id, idnumber (for user or course), shortname (for course), username or email (for user) ...

so you may call enrol_students with a wide combination such as

#using Moodle internal ids
enrol_students (2,'id', array (1,2,3), 'id')

# and course shortname
enrol_students ('chem101','shortname', array (1,2,3), 'id')

#or course idnumber
enrol_students ('thecourseidnumber','idnumber', array (1,2,3), 'id')

the students can also be specified by username

enrol_students ('thecourseidnumber','idnumber', array ('jdoe','psmith'), 'username')

or email

enrol_students ('chem101,'shortname', array ('jdoe@amce.com',....), 'email')

or students idnumber ...


When you call Web Service get_xxxx operations, the idfield does not even have to be unique such as

# get all users with Paul as firstname
get_users(array('paul'),'firstname')

# or get all users flagged as deleted
get_users(array(1),'deleted')


Cheers.

In reply to Patrick Pollet

Re: Problems with enrol_students

by Elliot Rapp -
Patrick and others,

I have a follow up question about add_user. I am calling this from magento and need to be able to create users based on the info available. I can do this but at the moment it appears as though we have to call setIdnumber for userDatum. This is problematic because I have to figure out the current highest ID for all users in the system and then add one as I don't have any magical number to assign to them. So far I haven't found any easy work around to accomplish what is basically just asking the system to set the next available ID.

Am I missing something?

Thanks,
Elliot

In reply to Elliot Rapp

Re: Problems with enrol_students

by Patrick Pollet -
Hi Eliot,

Glad to learn that magento do speak with Moodle across this Web Service.

Actually the idNumber is required by the WebService since it is in most external applications the only unique and reliable way to identify an user (e.g. student ID, social security number...), much more reliable that a login...

But, fortunately Moodle stores that idNumber in a varchar() field so it could be anything, even not a real number, as long as it is UNIQUE ... and Moodle never use it (it just display it from time to time) . But the Web Service uses it as the default way to identify an entity (user, course ...) when you want to modify or delete it.

Why not setting idnumber to be equals to magento's Login or even Magento's email ? That should be unique enough...

something like :

[code]

$user= new userDatum();
...
$user->setUsername('your magento login');
$user->setPasswordmd5('your magento md5 password so it will be the same in moodle if password salt are not enabled in Moodle !! ');
$user->setIdnumber('again your magento login');
$user->setFirstname(' your magento first name ');
$user->setLastname(' your magento last name');
$user->setEmail(' your magento email ');

$res=$moodle->add_user($lr->getClient(),$lr->getSessionKey(),$user);

[/code]

That should please the Web Service and make you happy wink

Cheers

In reply to Patrick Pollet

Re: Problems with enrol_students

by Elliot Rapp -
That is exactly the type of solution that I was looking for.

Thanks!


In reply to Patrick Pollet

Re: Problems with enrol_students

by Elliot Rapp -
Patrick,

I have another follow up. This one is a little different. I move the entire "clients" folder to my Magento install and am using the code in a module which fires off a given event. The direct SOAP calls work fine, for example:

require_once ('clients/MoodleWS.php');

$moodle=new MoodleWS();

$client = new SoapClient("http://oursite/magento/moodle/wspp/wsdl_pp.php");
$results = $client->login("foo", "foo");
$res=$client->count_users_bycourse($results->client,$results->sessionkey,
$idcrse,'shortname',0);
$usernametotest = $currentCustomerEmail;
$coursename = "coursefoo";
$userObjArray=$client->get_user_byusername($results->client,
$results->sessionkey,$currentCustomerEmail);

$userarray = (array)($userObjArray->getUsers());


The above works fine until I get to $userObjArray->getUsers() which results in the following error: Fatal error: Call to undefined method stdClass::getUsers()

What am I missing here?

Thanks!
Elliot


In reply to Elliot Rapp

Re: Problems with enrol_students

by Patrick Pollet -
Eliot,

You should not do it that way.

the variable $moodle that your create by $moodle= new MoodleWS() MUST be used to call the Web Service . Do not use a SoapClient() which is too basic and do not convert complex datatypes returned by WSPP to PHP classes... Actually you created the variable $moodle but never use it wink

so your calls to $client->login() and $client->count_users_bycourse($results->client,$results->sessionkey,
$idcrse,'shortname',0); seems to work because they return simple data that are mapped to a StdClass by SoapClient and you later get their attributes ($results->client,$results->sessionkey)
but the call get_user_byusername() returns an array of UserReturn instances and the SoapClient returns it as a simple StdClass with the attribute $users properly filled but not the method GetUsers(). I guess you can get the returned user by calling :

userarray = (array)($userObjArray->$users);


What you should do (see in clients/tests directory the script named test_get_user_byusername)

[code]
<?php
require_once ('../MoodleWS.php');

$moodle=new MoodleWS();
require_once ('../auth.php');
/**test code for MoodleWS: Get user info from Moodle user
login
* @param integer $client
* @param string $sesskey
* @param string $userinfo
* @return getUsersReturn
*/

$lr=$moodle->login(LOGIN,PASSWORD);
$res=$moodle->get_user_byusername($lr->getClient(),$lr->getSessionKey(),'someusername');
print_r($res);
print($res->getUsers());

$userarray = (array)($res->getUsers());

$moodle->logout($lr->getClient(),$lr->getSessionKey());

?>
[/code]

The appropriate MoodleWS.php script (adapted to your Moodle server) is to be generated ONCE by calling from somehere

php path/to/moodle/wspp/wsdl2php.php http://yourmoodleserver.org

see the INSTALL file shipped with WSPP.

Cheers.


php
In reply to Patrick Pollet

Re: Problems with enrol_students

by Elliot Rapp -
Patrick,

Thanks so much for the help. I guess I will have to continue to break down the array to access the individual elements (in particular 'error' to check for no match).

One question, why is this returned as a collection of users? I thought a username in Moodle was unique? Or is userinfo more generic?

Thanks,
Elliot


In reply to Elliot Rapp

Re: Problems with enrol_students

by Patrick Pollet -
> why is this returned as a collection of users?

It is a deliberate choice of conception to keep the size of the wsdl file to a minimum.
All get_xxxx return an array of record(s), even if only one is found or if it is obviously unique.

actually get_user_byusername() is a convenience operation that calls internally the much more powerful get_user/get_users operations that accept almost any single criteria. So no surprise that the result is always an array.

i.e.

// return these users (some of them may have error not empty if username is not found)

get_users($lr->getClient(),$lr->getSessionKey(), array('me','you','nobody'), 'username');

you may also use this one ( no need to put the criteria in an array) , and should get an array of users whose firstname is patrick :

get_user($lr->getClient(),$lr->getSessionKey(), 'patrick', firstname');
what's the point ? I don't know, maybe send them a greeting card on 17th of March ;)


>(in particular 'error' to check for no match).
yes the error field is extremely important and is always filled in case of trouble.

Cheers.

In reply to Justin Filip

Re: OKTech Web Services

by Jorge Fierro -
hello friends ..
I am testing the web services /wspp/clients/tests/test_get_all_forums.php of Web Services in moodle19 OKTech parameters required to obtain such information are:

/ ** Test code for MoodleWS: Get All Forums
* @ Param integer $ client
* @ Param string $ sesskey
* @ Param string $ fieldname
* @ Param string $ fieldvalue
* @ Return getAllForumsReturn
* /

The @ param integer $ client, and @ param string $ sesskey will get them from the function
$ Lr = $moodle->login($username,$password);

until this works correctly, but the problem is with the last 2 get_all_forums function parameters (,, $fieldname,$fieldvalue) as the information obtained for the forums.
$ Res = $moodle->get_all_forums ($ lr->getClient (), $ lr->getSessionKey (),'','');

What should be the values for the parameters
* @ Param string $ fieldname
* @ Param string $ fieldvalue


Another question as you can get using a Web services forums a particular course.
Thanks
In reply to Jorge Fierro

Re: OKTech Web Services

by Patrick Pollet -
Hi Jorge,

If you peek at source code in wspp/server.class.php (all real operations are performed there) you will see that :

- all get_all_xxx operations are simple wrappers to a get_records call with the appropriate search criteria, followed by a call to a filter_xxxx function that remove all results that the currently looged in user has no capacity to see , so :

- if the two parameters $fieldname and $fieldvalue are left empty, you will get all forums that user can see on the all Moodle site

- otherwise it will return all forums matching the criteria : $fieldname is the name of the column to test in the appropriate table and $fieldvalue the value to search

so

get_all_forums($ lr->getClient (), $ lr->getSessionKey (),'id',36) will return the forum with id 36

get_all_forums($ lr->getClient (), $ lr->getSessionKey (),'course',36) will return all seeable forums of course 36

get_all_forums($ lr->getClient (), $ lr->getSessionKey (),'type','news') will return all seeable forums of type News

and so on ...

Of course appropriate fieldvalue do depend of the table to search (label, assignment, database,quiz,chat,wiki ....). Typical use is definitively with fieldname='course' and fieldvalue= the Moodle course id (previously retrieved by some call to get_my_courses () or similar...


Alternatively you may use the call
public function get_instances_bytype($client, $sesskey, $courseids, $idfield = 'idnumber', $type)

that will return all 'seeable' activities of a given type ('forum', 'database','chat' ....) of an array of given courses identified by $idfield = $icourseid

such as
//return all forums of course whose idnumber is chem101 
 get_instances_by_type($ lr->getClient (), $ lr->getSessionKey (),array('chem101'),'idnumber','forum') 
Cheers

In reply to Patrick Pollet

Re: OKTech Web Services

by Jorge Fierro -
Hi Patrick Pollet
Thank you for your contribution, I was able to get it the forums of course. Using your post where the parameters are described in order to use the function get_all_forums ().

Using web services got the information the forum

A question for the forum to get it in discussions
Example:

getAllForumsReturn Object ([forums] => Array ([0] => stdClass Object ([error] => [id] => 11 077 [course] => 23 266 [type] => single [name] => "Theme discucion "[intro] =>
"Comments l".

A question for the replicas of the forum:
id = 11 077 .... In this forum there are N replicas of students to obtain the replicas that feature is used.

Mood Using the address that allows access to the replicas is:
mod / forum / discuss.php about, but with the use of which would be web services.

Thanks for help.
In reply to Jorge Fierro

Re: OKTech Web Services

by Patrick Pollet -
Sorry but I do not understand what you mean by replicas ?
Currently there are no Web Services operations to fetch forum posts nor to post a message to it...

Cheers
In reply to Patrick Pollet

Re: OKTech Web Services

by Jorge Fierro -
Hello Patrick Pollet ..

I would like to help me with some idea how I can get a list of all the responses that students have led to a proposed forum. By consulting the database on the Moodle working. Maybe if you know of any Web Servies that implements this function.

Please Tell me.

Thank you.
In reply to Patrick Pollet

Re: OKTech Web Services

by Oscar Peli -

Hi Patrick, can you help me?
I have the following issue:

If I call this url http://mysite/moodle/wspp/wsdl_pp.php I get the correct XML file

If I call this url http://mysite/moodle/wspp/service_pp.php I get the following error:
WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'http://mysite/moodle/wspp/wsdl_pp.php' : failed to load external entity http://mysite/moodle/wspp/wsdl_pp.php

Some suggestions?

Thanks

In reply to Oscar Peli

revision 1.6.4 is out

by Patrick Pollet -
hello,

Revision 1.6.4 has been committed today to Moodle 's CVS and project's page http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews

  • version 1.6.4 26/05/2010 download
    • added security cleaning of parameters for login operation and all $client and $sessionkey sent to subsequent operations
    • added support for custom profile fields
    • all get_user* operations now return the user's custom field profiles in an extra array
    • added operation get_users_byprofile($client,$sesskey,$profilefieldname,$profilefieldvalue) returning users having some value in a custom profile field such as $res=$moodle->get_users_byprofile($lr->getClient(),$lr->getSessionKey(),"groupePC","99");
    • added operation set_user_profile_values ($client,$sesskey,$userid,$useridfield,$values) allowing to set one or several custom profile fields for an user identified by $useridfield=$userid
  • version 1.6.3 13/04/2010 download
    • added get_courses_search operation, returning a list of courses having some strings in fullname, shortname, description or idnumber.

Enjoy.

sample php code of set_user_profile_values (see clients/tests/test_set_user_profile_values.php.sav) : that is set existing custom fields groupePC (type text) to 0, typeUser (type menu) to enseignant and prof (type chcekbox) to 1 :

require_once ('../MoodleWS.php');
$moodle=new MoodleWS();
require_once ('../auth.php');
$lr=$moodle->login(LOGIN,PASSWORD);
$values=array(new profileitemRecord('groupePC','0'),
 new profileitemRecord('typeUser' ,'enseignant'),
 new profileitemRecord('prof' ,'1'));
$res=$moodle->set_user_profile_values($lr->getClient(),$lr->getSessionKey(),'somelogin','username',$values);
print_r($res); 

In reply to Justin Filip

Re: OKTech Web Services

by Lailatul Hidayah -
Dear all,

I have installed OK Tech 1.6.5 in moodle 1.9
I have tested it using scripts in tests folder. I got a problem here. I tried test_get_courses.php, test_get_sections.php, and test_get_resources.php.
The first one is just fine. It shows all courses in my moodle. I tested it from local server and remote clients. But for the rest ( sections and resources), I got only one row when I tested it in remote clients but they work fine in local server.
Why did it happened? Please tell me how to resolve this issue. I really appreciate any help. Thank you.

Regards,

Luph.
In reply to Lailatul Hidayah

Re: OKTech Web Services

by Lailatul Hidayah -
I replied to my own post. I thought this is about parameter issue.
in test_get_resources.php , it needs :

/**test code for MoodleWS: Get resources in courses
* @param integer $client
* @param string $sesskey
* @param (getCoursesInput) array of string $courseids
* @param string $idfield
* @return getResourcesReturn
*/

then they are called in :
$res=$moodle->get_resources($lr->getClient(),$lr->getSessionKey(),$courseids,'');

what I confused is how to fill $courseids. Before that line, it is $courseids=array(); but I get no resources, all I got when I called this file is :

getResourcesReturn Object ( [resources] => Array ( [0] => stdClass Object ( [error] => noressources [id] => 0 [name] => [course] => 0 [type] => [reference] => [summary] => [alltext] => [popup] => [options] => [timemodified] => 0 [section] => 0 [visible] => 0 [groupmode] => 0 [coursemodule] => 0 [url] => [timemodified_ut] => ) ) ) Array

although indeed I have made sure that there are any resources in my moodle table.

How should I resolve this? Thank you for any replies.
In reply to Lailatul Hidayah

Re: OKTech Web Services

by Jorge Fierro -
Hi, the code get resources

<?php
require_once ('../MoodleWS.php');

$moodle=new MoodleWS();

require_once ('../auth.php');
/**test code for MoodleWS: Get resources in courses
* @param integer $client
* @param string $sesskey
* @param (getCoursesInput) array of string $courseids
* @param string $idfield
* @return getResourcesReturn
*/
if( $_SERVER['argc'] == 3 ) {
$username= $_SERVER['argv'][1];
$password= $_SERVER['argv'][2];
$course= $_SERVER['argv'][3];
} else {
$username = $_GET['username'];
$password = $_GET['password'];
$course= $_GET['courseid'];
}
$arrayF=array('id','name','course','reference','url','timemodified_ut');
$lr=$moodle->login($username,$password);
$courseids=array();
$res=$moodle->get_resources($lr->getClient(),$lr->getSessionKey(),'course',$course);

foreach ($res->getResources() as $arra) {
if (!$arra->error) {
foreach($arrayF as $field) {
$a=$arra->$field."|";
print($a);
}
print("\n");
}else {
print("$arra->error\n");
}
}

$moodle->logout($lr->getClient(),$lr->getSessionKey());

?>

Student's overwhelming resources separated by subject |

I hope you serve ..

In reply to Jorge Fierro

Re: OKTech Web Services

by Lailatul Hidayah -
Hi Jorge,
It's very nice to see your reply. Thank you. I had tried it and I think it worked since it comes out with a result, but the problem is that it is not my resource list. All I got is like this :

noressources

I have ensure that I do really have resources in my tables. So maybe this is not about parameter issue. And I think there is nothing wrong with my client-server connection since if succeed tried test_get_courses and test_get_roles. Is there any possibility that it is about authentication? courses and roles are items that don't ask user to log in to view, but resources did, only registered users can see. But in the code we have supplied login, so, what is this about??

So confusing for me...

Thanks for any help.
In reply to Lailatul Hidayah

Re: OKTech Web Services

by Patrick Pollet -
Hello,

I suspect that the account your are using to login to the web service has no capabilities to see any courses, thus the answer 'noressources' .There is no problem of communication since you got answer, but with the error field not empty.

For testing purposes you should use an account with admin privileges.
In that case, calling get_resources with an empty $courseids array (and a blank $courseidfield) should returns you ALL ressources in all courses, so an array with quite many entries. That's exactly the default values set in the script test_get_resources.php

@jorge : your parameters are wrong

$courseids=array();
$res=$moodle->get_resources($lr->getClient(),$lr->getSessionKey(),'course',$course);


it should be
$courseids=array(1,2,3);
$res=$moodle->get_resources($lr->getClient(),$lr->getSessionKey(),$courseids,'id');

this will return ressources visibles to logged-in user in courses whose ids are 1 2 or 3

or

$courseids=array('ashortname');
$res=$moodle->get_resources($lr->getClient(),$lr->getSessionKey(),$courseids,'shortname');

returns visible resources in course whose shortname is ashortname

Cheers.



In reply to Patrick Pollet

Re: OKTech Web Services

by Lailatul Hidayah -
Hi Patrick,

Thank you for your contribution.I have checked my auth.php to see the user. And It was actually user with admin privileges. I am so curious about this issue.I have tried to reinstall this OKTech but the result is just the same...

Best,

Lailatul
In reply to Justin Filip

Re: OKTech Web Services

by Eddie Walsh -
Hi,

Is it possible to return every grade item in a course using the OKTech web services?
I have the 'get_grades' and 'get_user_grades' functions working but they seem to only return the course total grade.

Thanks.
In reply to Eddie Walsh

Re: OKTech Web Services

by Raine Pyssysalo -
Hi,

I'm too having problems with fetching grades from moodle. I'm using the "base"-webservice. I'm trying to call method mdl_soapserver.get_grades with php-built-in-soap-client but it always returns 16 empty objects. It doesn't matter how I define the parameters. Does anybody have any suggestions?

Here's my code:

try{

$client = new SoapClient("http://localhost/moodle/ws/service.php?type=soap&wsdl");

$params = array();
$params["username"] = "username";
$params["password"] = "password";

echo "<pre>";
var_dump($client->__getFunctions());

//print_r($params);

$login_response = $client->__soapCall("mdl_soapserver.login", $params);

$grade_params = array();
$grade_params["client"] = $login_response->client;
$grade_params["sesskey"] = $login_response->sessionkey;
$grade_params["userid"] = "4";
$grade_params["courseids"] = array(2,3);
//$grade_params["idfield"] = "category";

$grade_response = $client->__call("mdl_soapserver.get_grades", $grade_params);

print_r($grade_response->grades);

//var_dump($grade_response);

$logout_response = $client->__soapCall("mdl_soapserver.logout", array("client"=>$login_response->client, "sessionkey"=>$login_response->sessionkey));

if ($logout_response)
{
echo "<br />Logout succesfull";
}

}catch(SoapFault $soa)
{
echo "Error: ".$soa->getMessage();
}


In reply to Raine Pyssysalo

Re: OKTech Web Services

by Patrick Pollet -
Hello,

Your syntax to call the Web Service looks strange to me... You should use an object-oriented syntax which is more simple !

see the sample script in clients/tests/test_get_grades.php (see the file INSTALL.TXT to create them)


require_once ('../MoodleWS.php');

$moodle=new MoodleWS();
require_once ('../auth.php');
/**test code for MoodleWS: Get User Grades in some courses
* @param integer $client
* @param string $sesskey
* @param string $userid
* @param string $userfield
* @param (getCoursesInput) array of string $courseids
* @param string $courseidfield
* @return getGradesReturn
*/

$lr=$moodle->login(LOGIN,PASSWORD);
$courseids=array();
$res=$moodle->get_grades($lr->getClient(),$lr->getSessionKey(),'','',$courseids,'');
print_r($res);
print($res->getGrades());

$moodle->logout($lr->getClient(),$lr->getSessionKey());

In your case , I suspect that the values 2,3 used for courses are Moodle ids (and not the default idnumber) and the value 4 for the user is also Moodle's id and not idnumber

so the central call should be

$courseids=array(2,3);
$res=$moodle->get_grades($lr->getClient(),$lr->getSessionKey(),'4','id',$courseids,'id');

Cheers.

In reply to Eddie Walsh

Re: OKTech Web Services

by Patrick Pollet -
Hi Eddie,

No, it is not possible yet and would be difficult to implement due to the wide variety of possible grades (format, hidden...) and calculation method used in Moodle.

I guess you can do it "manually" by exporting the gradebook to some spreadsheet format ...

Cheers.
In reply to Patrick Pollet

Enrolling students using Java

by Khalid Farouk -

Hi all,

i want to enrol a student in course using java.

I' am not able to init EnrolStudentsInput.

does any one have a sample xml for EnrolStudentsInput

This is my code

public void enrollStudent()

{

EnrolStudentsDocument enrolldoc = EnrolStudentsDocument.Factory.newInstance();

EnrolStudents enrol= enrolldoc.addNewEnrolStudents();

String xmlinput="<enrolStudentsInput xmlns:ns2=\"http://schemas.xmlsoap.org/soap/encoding/\" \n" +

"xsi:type=\"ns2:Array\" ns2:arrayType=\"xsd:string[1]\">\n" +

"<item xsi:type=\"xsd:string\">329</item>\n" +

"</enrolStudentsInput>";

EnrolStudentsInput enrollinput = null;

try {

enrollinput = EnrolStudentsInput.Factory.parse(xmlinput);

} catch (XmlException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

System.out.println("xml:"+enrollinput);

//enrollinput.setId("A00010397");

enrol.setCourseid("10112");

enrol.setCourseidfield("10112");

enrol.setUseridfield("329");

enrol.setClient(client);

enrol.setSesskey(sessionkey);

try {

System.out.println( stub.enrol_students(enrolldoc));

} catch (RemoteException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

In reply to Khalid Farouk

Re: Enrolling students using Java

by Patrick Pollet -
Hi Khalil,

According to the fragment code you sent, you are using the new axis 2.0 library (and not the 1.4 that I am more familiar with)... See http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews/some-success-with-the-new-axis-2-library/ for my only successfull attempt to call Web Services with axis 2.0 back in 2008.


Anyway, the call to enrol_students requires the following six parameters

1)an array of students ids. You seems to pack them in an XML string and parse it later , why ? why not creating directly a java Array ? I am not familiar with Axis 2.0 array passing... something like :

String[] thems={"329"};

enrol.setUserids (thems);


2)the course id as a string : your call enrol.setCourseid("10112"); looks good

3) the fieldname in Moodle database course's table to use to uniquely identify the course (could be "id" or "idnumber" )

so in your case I guess it should be enrol.setCourseidfield("id");

4) the fieldname in Moodle database user's table to uniquely identify the target user(s). Again it could be id, idnumber but also username or email...

so in your case I guess it should be enrol.setUseridfield("id");

and finally the credentials : your code looks good there

enrol.setClient(client);

enrol.setSesskey(sessionkey);


Also it will be interesting to know what errors messages are sent back by the Web Service in the catch blocks...


Cheers.



In reply to Patrick Pollet

Re: Enrolling students using Java

by Khalid Farouk -

Thank you Patrick for you help

My best regards,

Khalid

In reply to Justin Filip

Update_user raises the ws_userunknown error

by Khalid Farouk -

When I try to call update user in test_update_user.php  through oktech web services I got this error

 ws_userunknown

 Here is the sample xml request

Any idea

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsdl="CFGWWWROOT/wspp/wsdl">

   <soapenv:Header/>

   <soapenv:Body>

      <wsdl:update_user soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

         <client xsi:type="xsd:integer">41</client>

         <sesskey xsi:type="xsd:string">9e1fe51a27735aa108f08432f93401ca</sesskey>

        <user xsi:type="wsdl:userDatum">

            <!--You may enter the following 32 items in any order-->

            <action xsi:type="xsd:string">add</action>

            <id xsi:type="xsd:integer">0</id>

            <confirmed xsi:type="xsd:integer">1</confirmed>

            <policyagreed xsi:type="xsd:integer">0</policyagreed>

            <deleted xsi:type="xsd:integer">0</deleted>

            <username xsi:type="xsd:string">ahmed2</username>

            <auth xsi:type="xsd:string">manual</auth>

            <password xsi:type="xsd:string">Password@123</password>

            <passwordmd5 xsi:type="xsd:string">Password@123</passwordmd5>

            <idnumber xsi:type="xsd:string">1</idnumber>

            <firstname xsi:type="xsd:string">ahmed</firstname>

            <lastname xsi:type="xsd:string">ahmed</lastname>

            <email xsi:type="xsd:string">mm2@mm.net</email>

            <emailstop xsi:type="xsd:integer">0</emailstop>

            <icq xsi:type="xsd:string">a</icq>

            <skype xsi:type="xsd:string">a</skype>

            <yahoo xsi:type="xsd:string">a</yahoo>

            <aim xsi:type="xsd:string">a</aim>

            <msn xsi:type="xsd:string">a</msn>

            <phone1 xsi:type="xsd:string">a</phone1>

            <phone2 xsi:type="xsd:string">a</phone2>

            <institution xsi:type="xsd:string">a</institution>

            <department xsi:type="xsd:string">a</department>

            <address xsi:type="xsd:string">a</address>

            <city xsi:type="xsd:string">Cairo</city>

            <country xsi:type="xsd:string">EG</country>

            <lang xsi:type="xsd:string">en</lang>

            <timezone xsi:type="xsd:integer">99</timezone>

            <lastip xsi:type="xsd:string">n</lastip>

            <theme xsi:type="xsd:string">none</theme>

            <description xsi:type="xsd:string">desc</description>

            <mnethostid xsi:type="xsd:integer">0</mnethostid>

         </user>

         <idfield xsi:type="xsd:string">4</idfield>

      </wsdl:update_user>

   </soapenv:Body>

</soapenv:Envelope>

In reply to Khalid Farouk

Re: Update_user raises the ws_userunknown error

by Patrick Pollet -

Hi Khalid,

 

update_user expects as the fourth parameter the name of the column in Moodle's table mdl_user to uniquely identify the user to update that could be username, email, id or idnumber

 

Thus you should have <idfield xsi:type="xsd:string">username</idfield>  if it is the username .

 

No surprise that edit_users worked since in that case the idenfifying field is always Moodle's internal id (4 in your case ? )  I guess from your XML).

Plz also note that you should NOT send in the same time password and passwordmd5. password is meant for a clear password to be converted internally to md5 and passwordmd5 is for an already converted password ... passwordmd5 having priority if found

 

finally, you should send only the values you want to change . By default the webservice will ignore empty values ( empty strings and 0 numbers) . Thus the values for id, deleted, emailstop and mnethostid will be ignored .

Cheers.

Average of ratings: Useful (1)
In reply to Patrick Pollet

Re: Update_user raises the ws_userunknown error

by Khalid Farouk -

Thank you Patrick, we used update_users and it worked

My best regards

In reply to Justin Filip

add_category

by Khalid Farouk -

Hi All,

I need to add a new category, but with a specific "category ID". Every time I use add_category, it increments the ID in the table and doesn't use my ID. I need it to use the ID that I set using setID. Is there a way to force the web service to use the ID that I supply?

In reply to Khalid Farouk

Re: add_category

by Patrick Pollet -

Khalid,

 

It is impossible to set the category id when creating it, since it corresponds to an autoincrement field into Moodle's mdl_category table. Even if you force it to some value, the Moodle's API function insert_record will remove it before adding the record to the database.

Average of ratings: Useful (1)
In reply to Justin Filip

Enrol Teacher to a course

by Khalid Farouk -

I want to enrol a user as a teacher in course, should I use  affect_user_to_course method   in oktech or which method should be used

In reply to Khalid Farouk

Re: Enrol Teacher to a course

by Patrick Pollet -

@Khalid,

Yes affect_user_to_course is a general operation that requires the userid, courseid and the role shortname

See the following sample code in php adding user with username='toto' a new teacher to course idnumber='pp001'

<code>

<?php

require_once ('../MoodleWS.php');
$moodle=new MoodleWS();require_once ('../auth.php');

$lr=$moodle->login(LOGIN,PASSWORD);
//1) get the userid if not known by
$res=$moodle->get_user($lr->getClient(),$lr->getSessionKey(),'toto','username');
//print_r($res);
$userid=$res->users[0]->id;
//2) get the courseid if not known by
$res=$moodle->get_course($lr->getClient(),$lr>getSessionKey(),'pp001','idnumber');


print_r($res);

$courseid=$res->courses[0]->id;

if ($courseid && $userid) {

//and call

print ('uid='.$userid.' cid='.$courseid."\n");

$res=$moodle->affect_user_to_course ($lr->getClient(),$lr->getSessionKey(),$userid,$courseid,'editingteacher');

print_r($res);

} else

print "user or course not found";
$moodle->logout($lr->getClient(),$lr->getSessionKey());
?>

</code>

 

To remove this role, use

$res=$moodle->remove_user_from_course($lr->getClient(),$lr->getSessionKey(),3,4,'editingteacher');

Cheers.

In the forthcoming 2.0 compatible revision I shall add more 'user friendly' operations such as add_teacher, add_student, remove_teacher...

Average of ratings: Useful (1)
In reply to Patrick Pollet

Re: Enrol Teacher to a course

by Amit Bhatnagar -

This was very helpful.

How can I check if a user is already enrolled into a course so that I don't call the affect_user_to_course again?

In reply to Justin Filip

How to Enrol a student in a course that has an enrollment key?

by Khalid Farouk -

Hi All,

How do I Enrol a student in a course that has an enrollment key?, the enrol_student doesn't raise an error, but it doesn't enrol the student. The enrollment key should be removed for the web service to enrol the student. Is there a parameter to supply the enrollment key or to override it?

In reply to Khalid Farouk

Annoucment new version 1.7 Moodle 2.0 compatible

by Patrick Pollet -

Hello ,

I am annoncing here the new release, tagged 1.7 today.

version 1.7 22/10/2010 download

  • code compatible with Moodle 1.9 and Moodle 2.0 (automagically decides which version of Moodle to use).
  • added Moodle 2.0 specific cohort operations (add_cohort, delete_cohort, get_cohort_members, affect_user_to_cohort, remove_user_from_cohort, get_cohort_by*...)
  • added some missing groupings operations (get_grouping_byid, get_groupings_byname ... )

 

Updated documentation is at the usual place. http://cipcnet.insa-lyon.fr/Members/ppollet/public/moodlews

This revision will hit the Moodle's CVS in a few days if I can fix the new error message

[root@cipcnet wspp]# cvs commit -m "revision 1.7 Moodle 2.0 compatible"
cvs commit: Examining .
 cvs commit: Examining clients
cvs commit: Examining clients/lib 
cvs commit: Examining clients/tests 
cvs commit: Examining clients/zope
cvs commit: Examining clients/zsi
cvs commit: Examining dbLocal: 
Bad packet length 1349676916.
cvs [commit aborted]: end of file from server (consult above messages if any)

Enjoy.

In reply to Patrick Pollet

Re: Annoucment new version 1.7 Moodle 2.0 compatible

by Mayuresh K -

Hi Patrick,

Thank you for providing the updated version wspp 1.7

I have downloaded and tried to install wspp 1.7 as per the INSTALL file on Moodle 2.0 WAMP server .

When I login as Admin and goto Notifications (per the INSTALL file ) it just shows a message: 

"Enabling the PHP setting display_errors is not recommended on production sites because some error messages may reveal sensitive information about your server."

After going to Server Administration >> Development I do not see any option for OK Tech Webservices as described in the INSTALL file

However I am able to use SOAPUI to access the WSDL at the link http://localhost/wspp/service_pp.php, but when I try to invoke the login method with a user I created in Moodle (this user has all the privileges i.e. SOAP, XML-RPC and AMP) I get a error as below

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>Wspp Server</faultcode>
         <faultstring>ws_errorregistersession</faultstring>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

In the wspp_db_errors.log I see saw the errors corresponding to my login method call from SOAPUI :

Error reading from database\n#0 C:\Tools\moodlewamp\server\moodle\lib\dml\mysqli_native_moodle_database.php(732): moodle_database->query_end(false)
#1 C:\Tools\moodlewamp\server\moodle\lib\dml\moodle_database.php(1243): mysqli_native_moodle_database->get_records_sql('SELECT * FROM {...', Array, 0, 0)
#2 C:\Tools\moodlewamp\server\moodle\lib\dml\moodle_database.php(1215): moodle_database->get_record_sql('SELECT * FROM {...', Array, 0)
#3 C:\Tools\moodlewamp\server\moodle\wspp\wslib.php(79): moodle_database->get_record_select('webservices_ses...', 'userid = 3 AND ...', Array, '*')
#4 C:\Tools\moodlewamp\server\moodle\wspp\server.class.php(324): ws_get_record_select('webservices_ses...', 'userid = 3 AND ...')
#5 C:\Tools\moodlewamp\server\moodle\wspp\mdl_soapserver.class.php(228): server->login('wstestuser', 'Secret587@')
#6 [internal function]: mdl_soapserver->login('wstestuser', 'Secret587@')
#7 C:\Tools\moodlewamp\server\moodle\wspp\service_pp.php(39): SoapServer->handle()
#8 {main}Error reading from database\n#0 C:\Tools\moodlewamp\server\moodle\lib\dml\mysqli_native_moodle_database.php(407): moodle_database->query_end(false)
#1 C:\Tools\moodlewamp\server\moodle\lib\dml\mysqli_native_moodle_database.php(844): mysqli_native_moodle_database->get_columns('webservices_ses...')
#2 C:\Tools\moodlewamp\server\moodle\wspp\wslib.php(184): mysqli_native_moodle_database->insert_record('webservices_ses...', Object(stdClass))
#3 C:\Tools\moodlewamp\server\moodle\wspp\server.class.php(343): ws_insert_record('webservices_ses...', Object(stdClass))
#4 C:\Tools\moodlewamp\server\moodle\wspp\mdl_soapserver.class.php(228): server->login('wstestuser', ''Secret587@')
#5 [internal function]: mdl_soapserver->login('wstestuser', ''Secret587@')
#6 C:\Tools\moodlewamp\server\moodle\wspp\service_pp.php(39): SoapServer->handle()
#7 {main}

Can you please suggest if I am missing something. Any other steps that I need to take to get wspp 1.7 working on Moodle 2.0. The link for 'download'  (http://prope.insa-lyon.fr/~ppollet/moodlews/wspp_1.7.tgz)  in your post contains only one file named wspp_1.7[1]

Thanks

In reply to Mayuresh K

Re: Annoucment new version 1.7 Moodle 2.0 compatible

by Patrick Pollet -

@Mayuresh,

The errors came because Moodle 2.0 did not find the script local/wspp/settings.php nor the directory local/wspp/db , so the two new database tables were not created  when you went to Adminstration/Notifications. You MUST see some trace infos about the tables's creation and the new setting options...

I suspect you did not copy well the directory wspp/local/wspp into Moodle's local directory . You should have a directory nanmed wspp (with its sub dirs db and lang) at the first level of Moodle's local  as below

 

 

 

Cheers.

Attachment screenshot_042.png
In reply to Khalid Farouk

Re: How to Enrol a student in a course that has an enrollment key?

by Patrick Pollet -

@Khalid,

I do not find in the code why enrolment of a student would fail if course has an enrolment key and succeed if not. I would like to have more details on the error (Moodle version ...)

 

Cheers.

In reply to Justin Filip

Re: OKTech Web Services

by John Hunsley -

Hi,

 

Many thanks for creating the moodle ws package, its just what im looking for.

 

Does anyone have any doc which describes the input parameters for each operation. I'm having a hard time figuring out exactly what values I should supply in the SOAP requests for some operations.

 

For example -

get_events  requires the following params as well as authentication id and token:

 

<value xsi:type="xsd:string">2</value>
<id xsi:type="xsd:string">2</id>

 

I have no idea what these two values should represent, I'm guessing course id maybe???

 

Many thanks in advance.

 

John

In reply to John Hunsley

Re: OKTech Web Services

by Patrick Pollet -

Hi John,

 

You have three ways to find  the  nature and usage of parameters required by this Web Service, and to test them

1) you generate the php proxy classes and test scripts  by running the following command line in wspp/clients directory

php ../wsdl2php.php  http://youmoodle/wspp/wsdl_pp.php

this will generate a test script for all the known operations and will give you some hints about the parameters

for example clients/tests/test_get_events.php will have is its phpdocs comments  :

<?php
require_once ('../MoodleWS.php');
$moodle=new MoodleWS();
require_once ('../auth.php');
/**test code for MoodleWS: Get Moodle s events
* @param integer $client
* @param string $sesskey
* @param integer $eventtype
* @param integer $ownerid
* @return getEventsReturn
*/

...
?>


2) Alternatively, if you are familiar with javadoc you may consult the reference page at http://prope.insa-lyon.fr/~ppollet/moodlews/java/javadoc/

The java class containing all supported operations is named  MoodleWSPortType so you could start browsing the doc at

http://prope.insa-lyon.fr/~ppollet/moodlews/java/javadoc/localhost/moodle_20/wspp/wsdl/MoodleWSPortType.html

 

3) Finally you could use the SoapUI graphical interface to browse/test Moodle Web Service (see attached screenshot for exploring get_events operation).

Cheers.

 

Edit: of course you can also peek into the php code of the script wspp/server.class.php and find out that get_events function is requiring the following parameters :

 

$eventtype : could be

define('cal_show_global', 1);

define('cal_show_course', 2);

define('cal_show_group', 4);

define('cal_show_user', 8);

and then, depending of the $eventtype, the second parameter $ownerid will be either a courseid, a groupid or an userid. One of the most obscure operation BTW. Sorry wink

 

 

 



Attachment screenshot_041.png
In reply to Patrick Pollet

Re: OKTech Web Services

by John Hunsley -

Patrick, Many thanks for your detailed reply.

I am using the SoapUI v3.01. I see the generated request as shown in your screen shot.

I'm not sure what values to use for eventtype. I assume this is an enumeration, is this documented anywhere? I don't see the values specified in the javadoc.

If this detail is not documented I will just have to work it out by trial and error and will add the results to the javadoc and a tutorial.

If ownerid can be courseid then I'm guessing I'd need to call get_my_courses first to find the available courses, then check for events with another call to get_events for each course.

Anyway, just thinking out loud smile

Many thanks for your help

 

John

In reply to Justin Filip

get_messages

by John Hunsley -

Hi,

Is there a get_messages method in any version of the web service?

 

If not, is there any way I can access the  messages between course participants through the web service?

 

Many thanks

 

John

In reply to Justin Filip

get_quiz

by John Hunsley -

Hi,

Does anyone know what the quizformat string value parameters should be used in the get_quiz request?

 

My SOAP body of the request looks like this -

<client xsi:type="xsd:integer">x</client>
<sesskey xsi:type="xsd:string">xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</sesskey>
<quizid xsi:type="xsd:integer">2</quizid>
<quizformat xsi:type="xsd:string"></quizformat>

 

I am unsure what to put int he quizformat parameter, is this an enumeration? Is it documented anywhere?

 

Many thanks

 

John

In reply to John Hunsley

Re: get_quiz

by Patrick Pollet -

@John,

There are no operations yet to fetch Moodle messages between users...

The quizformat is the export format you want to use to fetch the quiz questions as if you were exporting it from Moodle . It could be any export format supported by Moodle such as xml, gift ... all of them are the subdirectory names in question/format.

 

Actually I only tested xml wink see in libquiz.php

 

/** * check that the requested export format is available */

function ws_libquiz_is_supported_format($format) { global $CFG; return is_readable($CFG->dirroot . "/question/format/$format/format.php"); }

 

 

Cheers.

In reply to Patrick Pollet

Re: get_quiz / error in libquiz.php

by Harry Bleckert -

@Patrick

I installed your oktech wspp and enabled web services using moodle2integration.
So far, all works fine, except get_quiz() which uses libquiz.php

I get these error messages:
Notice: Undefined variable: QTYPES in /var/www/moodle/wspp/libquiz.php on line 73 Fatal error: Call to a member function get_question_options() on a non-object in /var/www/moodle/wspp/libquiz.php on line 75

Do you have a revised version of libquiz.php or could you provide a hint how to fix this?

Your assitance would be greatly appreciated!

Cordial Greetings
Harry

In reply to Justin Filip

get_activities

by John Hunsley -

@patrick

Hi,

I'm trying to access the activities on a course using the get_activities operation. I'm not exactly sure what parameter values I need to put in my request.

Using SoapUI I see the following generated request -

<iduser xsi:type="xsd:string"></iduser>
<iduserfield xsi:type="xsd:string"></iduserfield>
<idcourse xsi:type="xsd:string"></idcourse>
<idcoursefield xsi:type="xsd:string"></idcoursefield>
<idlimit xsi:type="xsd:integer"></idlimit>

I take it iduser is the id of the user enrolled on the course and idcourse is the id of the course. idlimit is self explanatory.

What are iduserfield and idcoursefield?

When I try putting in the same values as I put in iduser and idcourse I get noactivites returned in the response body. Can you tell me what I should be putting in these param values?

The empty response does give me some clues about what I should expect in return. Is there anything in the activity record response which tells me what the activity actually is? What are the DLA, DLL, DFA and DCL fields?

I expect to get back a collection of activity records for things like Lessons, Forums, Quizzes. How do I distinguish between the types of activities I have on my course?

Many thanks in advance,

Kind regards,

John

In reply to John Hunsley

Re: get_activities

by Patrick Pollet -

@john,

 

You misunderstood the role of operation get_activities. It is meant to return all student 'logged' activities in a course. A bad move from me, but in French 'activité' means  'action' , not a 'Moodle activity'... so I mis-translated 'activité' to 'activity'.

So the parameters are the userid value and the useridfield that is the database column to use to identify uniquely that user such as username,id,idnumber or email , a courseid and the courseidfield that is again the database column to use to fetch this course such as id, idnumber or shortname...  If empty, actions of that user in all his courses are returned

 

for example

<client xsi:type="xsd:integer">100</client>
<sesskey xsi:type="xsd:string">15620620c260502274950dfbe907138c</sesskey>
<iduser xsi:type="xsd:string">jdoe</iduser>
<iduserfield xsi:type="xsd:string">username</iduserfield>
<idcourse xsi:type="xsd:string"></idcourse>
<idcoursefield xsi:type="xsd:string"></idcoursefield>
<idlimit xsi:type="xsd:integer">50</idlimit>

will returns all logged-in actions of user jdoe, identified by its username in all his courses

 

and changing to

<idcourse xsi:type="xsd:string">CHEM 101</idcourse>
<idcoursefield xsi:type="xsd:string">idnumber</idcoursefield>

 

will returns its actions in course whose idnumber is CHEM 101

 

DATE,DFA, DLA, DLL and the rest where meant to convert the return Unix stamps time,firstaccess, lastaccess, lastlogin, currentlogin... to localized strings but are not implemented since I got SOAP errors with months names with accentuated characters, so they are always empty. See line 369 of script filterlib.php

 

What you are looking for is likey get_instances_bytype that return all instances of Moodle activities of a given type (such as forum, wiki, lesson, data ...)  in a set of courses or if empty in all courses that current user can see .

for example

<client xsi:type="xsd:integer">100</client>
<sesskey xsi:type="xsd:string">15620620c260502274950dfbe907138c</sesskey>
<courseids xsi:type="wsdl:getCoursesInput" soapenc:arrayType="xsd:string[]"/>
<idfield xsi:type="xsd:string">id</idfield>
<type xsi:type="xsd:string">forum</type>

return all forums in all courses

 

and

<client xsi:type="xsd:integer">101</client>
<sesskey xsi:type="xsd:string">81c7772ee6e4a1c579afe119d9d2fd4c</sesskey>
<courseids xsi:type="wsdl:getCoursesInput" soapenc:arrayType="xsd:string[1]">
<item xsi:type="xsd:string">3</item>
</courseids>
<idfield xsi:type="xsd:string">id</idfield>
<type xsi:type="xsd:string">forum</type>

 

return all forums in course identified by Moodle id=3

 

Alernatively you may use get_all_xxxx () operation that returns all xxx Moodle activities that current user can see matching one optional criteria  such as

<client xsi:type="xsd:integer">101</client>    
<sesskey xsi:type="xsd:string">81c7772ee6e4a1c579afe119d9d2fd4c</sesskey>
<fieldname xsi:type="xsd:string">course</fieldname>
<fieldvalue xsi:type="xsd:string">1</fieldvalue>

get all quizzes in course=1

 

Currently there is no operations to return 'all Moodle activities' of ant type registered in a course...

 

Cheers.

 

Edit : I really must find some time to document all operations will sample codes in PHP, Java, python and SoapUi XML...  on some Wiki , may be hosted on Moodle.org ?

In reply to Patrick Pollet

Re: get_activities

by John Hunsley -

@patrick

Many thanks for your detailed reply Patrick.

Does get_instances_bytype return Lesson activities? i.e. is there an enum type for lessons in the request param, e.g.

<type xsi:type="xsd:string">lesson</type>

 

I'll be happy to help document the params, a wiki would be best.

 

thanks again

 

John

In reply to John Hunsley

Re: get_activities

by Patrick Pollet -
No whatever module name, as registered in table mdl_modules can be used. If you mistype it, it will just say "nothing found" against Moodle 1.9 and a Soap execption against Moodle 2.0. Of course you will get a very basic answer as extracted from table mdl_course_modules as exposed in resourceRecord. Cheers.
In reply to Justin Filip

Re: OKTech Web Services

by Moodle Geek -

Hi, I am new to MoodleWS. To get started, I downloaded Ver. 1.6 which came in a zip file. When I extracted the zip file, I was expecting all the related WS folders and files to be extracted. However, i found a single large file which in return seems to contain the MoodleWS files. It's really confusing to me. Am I doing something wrong (for sure)? How can I extract those files?

In reply to Moodle Geek

OKTech Web Services Rev 1.8 is out

by Patrick Pollet -

Hello,

  • version 1.8 dated 27/12/2010 download Not anymore on Moodle's CVS repository (no more write access to contrib area due to Moodle's migration to git)
    • added forums (get_forum_discussions, get_forum_posts, forum_add_discussion, forum_add_post) and messaging (get_messages, get_messages_history, send_message) operations upon request of John Hunsley
    • reorganized code generation for php clients (wsdl2php) by putting proxy classes in a classes directory
    • support for a simplified version of the wsdl generated by WSHelper utility (use http://yourmoodle/wspp/wsdl_pp2.php instead of http://yourmoodle/wspp/wsdl_pp.php when generating your proxy classes by wsdl2xxx utilities or against SoapUI)
    • fixed duplicate definition of get_my_cohorts in wsdl.

I am starting documentation on Moodle docs here : http://docs.moodle.org/en/Web_Services:OK_Tech_Web_Services Feel free to contribute.


Season's greetings.

In reply to Patrick Pollet

Re: OKTech Web Services Rev 1.8 is out

by Angelo Nardi -

Patrick,

I'm using the rev. 1.8 and I notice a difference between the method add_user and update_user. 
The first method require a single apostrophe (') in the parameter value as expected. Instead, in the second method i Must to specify the apostrophe twice (''). 
This is a know issue?
How I can correct It?

thanks

In reply to Moodle Geek

Re: OKTech Web Services

by Patrick Pollet -

Hello,

 

MoodleWS never came out as a zip archive but a tgz, made under Linux with tar & gzip commands. I guess you have to install on your Windows workstation the proper software to extract it.

 

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by Catalin Maican -

Is it possible to extend the WS for obtaining the answers for a quiz by users?

If not could you, please, point me to some PHP files where I can get the SQL statements for these operations?

Thank you,
Catalin

In reply to Catalin Maican

Re: OKTech Web Services

by Patrick Pollet -

@catalin,

No you can only export a quiz (in XML format) but not the answers given by students ; you can also export grades .

I is unlikely that exporting student's answers will be ever implemented due to the vast number of question types available...

You may have a look at scripts mod/quiz/report/* to get an idea of the complexity of the task wink

In reply to Patrick Pollet

Re: OKTech Web Services

by Luis Eduardo Rios Castillo -

Hello Patrick and everybody!

I am trying to prove ws 1.8 last version.
I can install it on my Moodle 1.9 following the instructions,
but now I try to test with all clients and it gives me error test
fault: Invalid username or password.

You can help me I tell me what I'm doing wrong.


Thanks ..


In reply to Luis Eduardo Rios Castillo

Re: OKTech Web Services

by Luis Eduardo Rios Castillo -

I forgot

the username anp pasw are correct but i can't connect, maybe there is someone especial file that i have to edit to this work correctly,

tanks

In reply to Luis Eduardo Rios Castillo

Re: OKTech Web Services

by Patrick Pollet -

@Luis,

Gives us more details about what you are trying to do (langage of your clients...). If you talk about the test scripts written in php in wspp/clients/tests, you have to rename wspp/clients/auth.php.dist to auth.php and edit it to give the target login & password.

In reply to Patrick Pollet

Re: OKTech Web Services

by Esteban Chamba Jimenez -

Hi, I've tested the client using "Manual Account" how uthentication method, and  all is well, but when I am using "Web Services" how authetication method, I get a error "Uncaught SoapFault exception: [Wspp Server] Invalid Client connection". I am using moodle 1.9 and WSPP plugin.

I don't know how I authenticate from the client, I'm using this: "$lr= $moodle->login("user","pass");"

Sorry for my bad English

In reply to Justin Filip

Re: OKTech Web Services

by Florian Bernstein -

Hi everybody,

I'm trying to get familiar with the OKTech Services and installed the Service on a Moodle 2.0 test system. The services work but I'm a little bit confused about the authentication.

The documentation says that with Moodle 2.0 the new authentication plugin for web services which already comes with moodle will be used for authenticating the web service users.

For me that means, I can use the web service user I created for the Moodle 2.0 native web services and use his security token to use the services. But how should I pass the token?

Perhaps someone can explain this a little bit deeper.

In reply to Florian Bernstein

Re: OKTech Web Services

by Patrick Pollet -

>For me that means, I can use the web service user I created for the Moodle 2.0 native web services and use his security token to use the services. But how should I pass the token?

 

No not its security token but his login/password. You have to enable the Web Service Authentification plugin and create an user having this authentification method (like it was in Moodle 1.9). The only difference is that in Moodle 1.9 you had to install the authentification plugin (that was provided in the WS zip) and it is now built-in Moodle 2.0.

 

You provide them by first calling the login(username,password) operation that returns you a client ID and a session key that are later requested in all subsequent operations, including the final call to logout().

In reply to Patrick Pollet

Re: OKTech Web Services

by Florian Bernstein -

Ah ok! Thanks for the explanation. ;)

You've done a greate job with these services.

 

One more question. I searched the list of available web service function looking for a operation to get all courses of a person he or she is in some way related to (, as teacher or student). On the first look I couldn't find such a function. What would be the best way to get this information?

In reply to Florian Bernstein

Re: OKTech Web Services

by Florian Bernstein -

Ok, obviously I'm blind! I overlooked the functions get_my_courses, which does what I was looking for.

In reply to Florian Bernstein

Re: OKTech Web Services

by Patrick Pollet -
And don't forget that besides basic informations about the course(s) the WS add a numeric attribute named 'myrole' that gives a very crude information about the user's role in that course
1= admin, 2=course creator, 3=editing teacher, 4= non editing teacher, 5 = student.
see function ws_get_primaryrole_incourse() in wspp/wslib.php
Cheers.
In reply to Justin Filip

Re: OKTech Web Services upload scorm file

by Virginia Modrego -

Hi.

I've installed in my PC moodle2 with OKtech. I can access with web service java client to my moodle without problems.

I can create a new course with the web service, but I don't know how upload the scorm package into the course, with the web service. Is this possible?

Thanks for all.

In reply to Virginia Modrego

Re: OKTech Web Services upload scorm file

by Patrick Pollet -
> I can access with web service java client to my moodle without problems
Glad you made it wink Please don't hesitate to complete the current documentation with Java sample codes http://docs.moodle.org/en/Web_Services:OK_Tech_Web_Services#Writing_a_client_in_Java
We are missing examples (execpt with axis-1.4 library)
> don't know how upload the scorm package into the course, with the web service
It is not possible. The Web service do not have operations to upload anything to a Moodle course, no even a simple resource file.
Cheers.
In reply to Justin Filip

Re: OKTech Web Services

by Karolis Kriščiūnas -

Hello all,

I'm using OKTech Web Services to "integrate" drupal and moolde. When user creates a profile in drupal, he's enrolled to the list of courses (the courses id array's length is 10 ) and to the group in each course. This works great in most cases, but sometimes i get strange error "vous n'avez pas les permissions de faire cela." which, thanks to google translate, means 'you do not have permission to do that.'. Result of this is that user is enrolled only to 5 or 6, but not all 10 courses... I login using moodle's super admin. The source where user is enrolled to the courses is:


function add_group_to_moodle($drupal_users_id = array(), $groupname = '',
        $courseids = array(), $config = array()) {
	try{
		$moodle = moodlews_service_object($config);
		$lr = moodlews_login($moodle, $config);
		if (!$moodle || !$lr) {
			drupal_set_message(t('Failed to login to Moodle, try again later'), 'error');
			return;
		}

		// Add users to group
		if (count($drupal_users_id) > 0) {
			foreach ($drupal_users_id as $drupal_user_id) {
				$moodle_user_id = $moodle->get_user_byidnumber($lr->getClient(), $lr->getSessionkey(), $drupal_user_id);

				if ($moodle_user_id->users[0]->id != 0) {
					foreach ($courseids as $courseid) {
						//create group if group not exists or get the group id otherwise
						$moodle_course_group_id = _create_group($lr, $moodle, $groupname, $courseid);

						// Group exists OR created succesfully
						if ($moodle_course_group_id != -1) {
							$moodle->affect_user_to_course($lr->getClient(), $lr->getSessionkey(),
									$moodle_user_id->users[0]->id, $courseid, 'student');
							$ret = $moodle->affect_user_to_group($lr->getClient(), $lr->getSessionkey(),
									$moodle_user_id->users[0]->id, $moodle_course_group_id);
							watchdog('add_to_course', 'Add user to group '.$moodle_course_group_id.' in course '.$courseid , NULL);		
						} else {
							drupal_set_message(t('Can not create group!'), 'error');
							watchdog('add_to_course', 'Can not create group! '. $e->getMessage(), NULL);
							return false;
						}
					}
				}
			}
		}
		$moodle->logout($lr->getClient(), $lr->getSessionKey());
	} catch (Exception $e)
	  {  
		watchdog('add_to_course', $e->getMessage(), NULL);
	  }
}

 

$drupal_users_id array length is 1;  $courseids array length is 10.

Where could be a problem? Is it timeout or something? I'd appreciate any help...

In reply to Karolis Kriščiūnas

Re: OKTech Web Services

by Patrick Pollet -

Hello,

Hey interesting piece of code BTW wink

The problem to solve first is which one of the three calls to the WS is throwing the 'permission error'  i.e when :

  • you create (if needed)  the Moodle's group in _create_group($lr, $moodle, ... call
  • you affect the user to the course
  • you affect user to the group

This could be found by putting WS in full debug mode (see admin settings) and looking into moodledata/debug.out file for the latest error messages.

 

I don't think it is a timeout error, otherwise you will get a session has timed out error. I suspect that some of the $courseid you are sending from Drupal do not match the corresponding Moodle's course ids thus it cannot the find the appropraite context in which to check for permissions.

Are you sure that you always set the $group->courseid to the proper value in your function _create_group (especially if it does not exist yet) ? the WS needs it to retrieve the course's context ...

 

Cheers.

 

 

 

Cheers

Edit : if you download the latest version from git, https://github.com/patrickpollet/moodlews you should find a proper english translation file  in wspp/lang/en_utf8 that you should copy (or symlink)  in you moodledata/lang/en_utf8_local directory (or lt_utf8_local I guess).

Thanks to Stephen C. Scherer wink

In reply to Patrick Pollet

Re: OKTech Web Services

by Karolis Kriščiūnas -

Hi Patrick,

Thanks for your answer. Yes, i'm sure i set courses ids when creating groups and i'm sure i know exact moodle's courses ids, because there're only 10 courses and they're the same for every user.

It looks that i get this problem when more than one user is being enrolled to the list of courses at the same time, i mean when more than one user executes the piece of code above... The problem is that situation, when many users are creating their profiles and being enrolled to the courses at the same time, is common in our case.

In reply to Justin Filip

Re: OKTech Web Services

by Virginia Modrego -

I have successfully installed oktech in moodle2.0. I am now trying to install it in moodle 1.9, but moodle doesn't create the tables in the database.

The steps that I followed are the explained in install.txt

MOODLE 1.9 :---------------
2) copy wspp/lang/fr_utf8/local_wspp.php (and possibly other languages files) into your moodledata/lang/en_utf8_local folder . You may have to createthis folder. This will prevent future upgrades of moodle languages packs toerase it.


3) edit moodle/admin/settings/misc.php and add the line 
require("$CFG->dirroot/wspp/admin/wspp.php");       just before this line      // hidden scripts linked from elsewhere


4) go to the Administration of your Moodle site and set the new configuration options. You may later modify them in Administration/misc/OK Tech Webservice area. For first testings make sure ws_enforceipcheck is off...

5) Note that the database upgrade is done at the first call ever made to the WebService  (even unsuccessfull). It will add two tables mdl_webservices_sessions and   mdl_webservices_clients_allow

¿any ideas?

In reply to Justin Filip

Re: OKTech Web Services

by Virginia Modrego -

I have successfully installed with moodle2.0 oktech. I am now trying to install moodle 1.9, but I can't create the tables in the database.

I followed the steps that are explained in install.txt

MOODLE 1.9 :---------------
2) copy wspp/lang/fr_utf8/local_wspp.php (and possibly other languages files) into your moodledata/lang/en_utf8_local folder . You may have to createthis folder. This will prevent future upgrades of moodle languages packs toerase it.
3) edit moodle/admin/settings/misc.php and add the line 
require("$CFG->dirroot/wspp/admin/wspp.php");       just before this line      // hidden scripts linked from elsewhere
4) go to the Administration of your Moodle site and set the new configuration options. You may later modify them in Administration/misc/OK Tech Webservice area. For first testings make sure ws_enforceipcheck is off...

5) Note that the database upgrade is done at the first call ever made to the WebService  (even unsuccessfull). It will add two tables mdl_webservices_sessions and   mdl_webservices_clients_allow

 

this step 5) is the problem

any idea?

In reply to Virginia Modrego

Re: OKTech Web Services

by Ramakant Kulkarni -

I am using OKTECH web services. Is there a way a single user can access moodle via web service and a browser based interface? I want a mobile client as a convenience but for heavy duty work, I want the users to use the web based interface to my moodle installation. Is this possible? Any pointers or available solutions?

In reply to Ramakant Kulkarni

Re: OKTech Web Services

by Patrick Pollet -
In reply to Patrick Pollet

New Install gives Zero Content Length response

by John Hunsley -

Hi,

I have a new Moodle install (1.9.10) and installed the ws_1.8 package as per the install guide. I can see the webservices settings in the Misc' options in Moodle as the admin.

I can connect with soapUI from a remote client and generate the request but when I run any request, e.g. login with valid credentials I get a zero length response from the server.

 

Heres the raw Http data for my login request -

HTTP/1.1 200 OK
Date: Thu, 17 Feb 2011 12:53:29 GMT
Server: Apache
X-Powered-By: PHP/5.1.6
Set-Cookie: MoodleSession=dfj22r17lagoilaq6vbplsg1i4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: MoodleSessionTest=7lIUa7SEOi; path=/
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

 

No xml is returned, no valid response or error.

 

Please help smile

In reply to John Hunsley

Re: New Install gives Zero Content Length response

by John Hunsley -

Solved it! I ran ./mkclasses.sh and got and error -

PHP Fatal error:  Class 'SoapClient' not found in /var/www/html/moodle/wspp/wsdl2php.php on line 105

So I guess I dont have the Php Soap package installed -

yum search soap | grep php

tells me I need the Soap package and then install it -

yum install php-soap

restart apache and my requests now return a valid response.

 

I love it when a plan comes together tongueout

 

John

In reply to Justin Filip

Re: OKTech Web Services

by Jose Raul Perez -
Hi

I'm trying to use your web OKTech Web Services, just I noted two problems (that probably are mine because I don't know how to use it correctly):

- 1º, when moodle links points to this: /mod/assignment/view.php?id=8 , actually are pointing to assignment id=1 (for example). Because are not pointing directly to the id in table assigment.. well, I guess you allready know, so, it's possible to use this "id=8" to take the assigment from web service? .. I didn't find a way

- 2º, I noted that the object "assignment" it's little diferent from the table (I'm using moodle 2.0). The difference is that the object has the property "description" and in table, the correct column name is "intro" .. so, I guess this is wrong. I don't know where to change that, (I found the classes, and the process to input data, but there is something else I don't find because I have errors)..

By the way, you made it a very good work!! I'm gonna use it for my final project of university smile

Thanks
In reply to Jose Raul Perez

Re: OKTech Web Services

by Patrick Pollet -

Hi Jose,

 

Point 1 : For some obscure reasons known to Moodle core programmers (performance ?) , the id passed to scripts view.php is not the instance id of the module xxxx in the table mdl_xxxx but the id of a record in table mdl_course_modules from which they later retrieve the actual instance id ... see top of script mod/assignment/view.php the process of the two possible parameters id or a ...

Web Services cannot play that game. We offer a lot of operations to retrieve Moodle's entities and for consistency, the id returned is always the instance id in the appropriate table. So external clients could later on rely on this id to get more data. As an example you may call get_instances_bytype(....,'assignment') to get all assignments in a course and them for each of them use the  returned id to fetch its submissions... Assignments submissions are related to assignment instance id and not all to its 'relative position' in some course.

 

Point 2 : Yes, Moodle core programmers decided to rename about a dozen of columns from Moodle 1.9 to Moodle 2.0 ... The intro field of assignment is one of them. Problem is if I change the WSDL, it will break Moodle 1.9x clients unless all existing Web Services clients are recompiled !

Again WebService clients cannot be changed everytime some database fields are changed by decisions taken in Perth...  It is my problem to provide a 'consistent naming scheme' for attributes in the WSDL  and to process it internally to match the current real database name upon input and output operations...    So in the WSDL, fields previously named description will stay that way and will be internally converted to intro (if needed).

Give me a week or so to provide  fixes on the git repository of this project https://github.com/patrickpollet/moodlews that will no break existing clients ( smartphones, Universities SIS, external grading systems ...).

 

 

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

hello

In my final university project , I use OKtech web services provided by moodle to create a Android Client for Moodle Plateform. But unfortunetly until now I'am not able to retreive data from the server no matter what is the method i'am calling as a web sevice in android. The emulator always give me exceptions.First of all, is it possible to use OKtech web services contained in WSPP folder to implement an Android Client ?,

thanks in advance

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by Patrick Pollet -

Yes, there are examples around on Android using the KSoap2 java library that works nicely with the WSDL emitted by OK Tech WS.

Actually KSoap2 also works on a regular PC, so you do not need Android emulator to start experimenting.

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

thanks for the fast replay

Actually I need to run the connection between Oktech web services and my Android application : here is my code for invoking "login" method :

package telnet.education.androodle;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


public class LoginPage extends Activity {

private static final String SOAP_ACTION = "http://10.0.2.2/moodle/wspp/wsdl#login";

private static final String OPERATION_NAME = "login";

private static final String WSDL_TARGET_NAMESPACE = "http://10.0.2.2/moodle/wspp/wsdl";

private static final String SOAP_ADDRESS = "http://10.0.2.2/moodle/wspp/wsdl_pp.php";

@Override
public void onCreate(Bundle savedInstanceState)  {
super.onCreate(savedInstanceState);

TextView textView = new TextView(this);

setContentView(textView);

SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
request.addProperty("username", "admin");
request.addProperty("password", "Shevchenko-7");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = false;

envelope.bodyOut=request;

HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

try

{

httpTransport.call(SOAP_ACTION, envelope);

Object response = envelope.getResponse();

textView.setText(response.toString());

}



catch (Exception exception)

{

textView.setText(exception.toString());

}


}
}

This code throws me a xmlpullparserexception, it means that the server is sending me html while I'am waiting for a xml response .I'am stucked in here since a week ! my project is in danger please help.

Can you please provide me a code sample written in android that invok a Oktech web service so I can compare and figure out what's wrong.

thanks

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by snadly Mohamed Amine -

hi

Another thing : when i pull my http://localhost/moodle/wspp/wsdl_pp.php into my firefox browser I get a redirection box that get me to the wsdl file (written on xml) .But i think that in order  to verify that the web services are fonctionnal, the url mentionned above must produce the contract listing all the operations provided within the wsdl file. That's why I get the xmlpullparser exception : expected (start_tag <html..............).

Android is expecting a html file (the one listing the opertions ) , but instead it is redirected to an xml file (the wsdl) , so the exception is raised !!!!!

How to fix such a problem?

Greetings from Tunisia

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

hi patrick

Are you saying that the wsdl emitted by the okteck web services works nicely with the ksoap2 library ?

My project is to develope an android application for some moodle fonctions. but for now and after one month of research and tries, I 'am not able even in parsing the wsdl of okteck web services with android , however it works nicely with java (with wsdl2java clients).

And I tried putting these java stubs as a library in my android project , but it gaves me a build error beceause the dalvik (android virtual machine) doesn't support java rmi (the remote invocation method in java).So no way to use the java clients within android application.

This is really frustrating, and I'am out of solutions man.

Please help

In reply to Patrick Pollet

Re: OKTech Web Services

by Patrick Pollet -

Hi Jose,

Revision 1.8.1 is on github. let me know if it fix your problem with database column renamed in Moodle 2.0

Cheers.

In reply to Justin Filip

Re: OKTech Web Services

by Jose Raul Perez -
Hi

Well.. I'm still working with assignments web services.

I can't make it works get_assignment_submissions().. I guess this call is correct, doesn't it?
get_assignment_submissions($lr->getClient(),$lr->getSessionKey(), $idAssignment, $idUser,'',0); .. always I receive and empty array.. maybe some change with moodle 2 ?
Sorry, I can't contribute with some info in that issue.. I didn't find errors in database or others places...

I hope to help soon and not only to ask, but still I'm learning your code.. it doesn't exists something to add or edit submissions right?

Thanks
In reply to Jose Raul Perez

Re: OKTech Web Services

by Ramakant Kulkarni -

Assignment submissions is tricky. Firstly, there need to be assignments and related submissions. Then you need to have the role of the teacher for that course to see the submissions (I spent some time gazing at the empty results before it clicked that I was not looking through the correct userId smile.

A general approach, that I found useful, is to use a web service client like SoapUI to test the result of your webservice call (that will remove any suspiction on your own code that accesses the webservice). Once it works in SoapUI, job is easy, to replicate the results in your code.

Average of ratings: Useful (1)
In reply to Ramakant Kulkarni

Re: OKTech Web Services

by Patrick Pollet -

Hi Ramkant,

Nice advice abour SoapUI. The latest version of OK Tech on github now allow to see also its OWN submission(s) so I student can check was he has uploaded.

See previous post for current limitation to Moodle 1.9 for retrieving assign,men submissions. Work is in progress in that direction...

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by Ramakant Kulkarni -

Thanks Patrick, I am still on 1.9 hoping to move across soon, this tip surely helps and expedits my decision.

In reply to Patrick Pollet

Re: OKTech Web Services

by Jose Raul Perez -
I'm very very very happy to say this:

My first little contribution for OKTech Web Services, I made first approach of get_assignment_submissions for Moodle 2.0, now a student can see his submission (I tested online submission and one file submission, probably more than one file, works too).

So, you can see it here (just a fork of main project):
https://github.com/joseraul/moodlews/blob/master/wspp/server.class.php

Only for Moodle 2.0 !!

Cheers !!!
In reply to Jose Raul Perez

Re: OKTech Web Services

by Patrick Pollet -

Hi Jose,

Nice addition. I have added some notes on your commit at github wink

 

Cheers

In reply to Patrick Pollet

Re: OKTech Web Services

by Jose Raul Perez -
Hi Patrick

New little revision of get_assignment_submissions with some of your suggestions.

I have created new function, update_submission, it "works" for online submission and one file submission, only tested in Moodle 2.x. But The problem is that I don't know how to register the webservices function.. I have tested outside of the webservices but using same logic. Could you help me in this steps? in to register the new function?

All the work is here, https://github.com/joseraul/moodlews/blob/master/wspp/server.class.php

Lots of thanks.
In reply to Jose Raul Perez

Re: OKTech Web Services

by Patrick Pollet -

Hi José,

 

1) you have to add the same function declaration in class mdl_soapserver.class such as +  function update_submission ($client, $sesskey, $assignmentid, $userid, $newData, $files) {} and that function must call the parent function

2) depending of the return type (simple, object or array of objects) the syntax is different :

  • if you return a simple type , juste return it (see function logout)
  • if you return an object, you have to call the to_soap() function to wrap it in a known php class whose name is passed in parameter . See for example functions affect_xxxx_to_xxxxx that return an affectRecord
  • il you return an array of objects, you have to call to_soaparray() instead. See function get_roles().
  • to start with, you should try to return something simple and not a new type of Record.  AffectRecord with an error flag and an error message is easy to use . See function send_message() in server.class.php for an example of 'filling' it. wink

3) then, and it is the most tedious part you have to update the WSDL for your new operation :

  • if you use the old WSDL, i.e; you call http://yourmoodle/wspp/wsdl_pp.php you have to do it by hand by editing file wspp/moodlewsdl.xml  (see docs on cipcnet to see all sections that must be modified; that really difficult and error prone)
  • I recommend that you switch to the new way, i.e. calling the Web Services by http://yourmoodle/wspp/wsdl_pp2.php . then you just have to add PHP docs comment at the beginning of your new function in the class mdl_soapserver.class.php (@param AND @return)  and run the provided utility genwsdl.php that will produce a new wsdl file named moodlewsdl3.xml. If pleased with the result, SAVE  YOUR CURRENT file moodlews2.wsdl somewhere and copy moodlewsdl3.xml to moodlewsdl2.xml... and test using SoapUI and call http://yourmoodle/wspp/wsdl_pp2.php ...
  • If you ever change the number of the type of parameters of your function update_submission you must repeat this process.
  • When OK I shall take care of the 'manual way' to update the old WSDL for 'old clients'  that cannot be recompiled everyday...

Good luck.

Edit : Let's try to work by regular email instead of using this forum until we reach a final solution wink  My mail is pp[at]patrickpollet[dot]net

 

Edit2 : Have you got some news of some german students that are also looking for this extension ( but for Moodle 1.9x which is simpler, I think).

In reply to Jose Raul Perez

Re: OKTech Web Services

by Patrick Pollet -

Hi Jose,

 

get_assignment_submissions() is not currently working with Moodle 2.0 due to major changes in file storage API.

there is nothing yet available to add/edit submissions for the very same reason

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

Hi moodlers,

I 'am wondering if there is an oktech web service that upload a file (add it under  a specific course). It's an important feature, also a web service that download a file from a specific course ?

Best Regards

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by Patrick Pollet -

Not yet, but you are welcome to implement it

see https://github.com/patrickpollet/moodlews/wiki/Extending-the-moodle-ws

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

hi patrick

I am using your java library , and my question is : how can I get the role of a specific user using the ok tech web services (including wsdl1 and wsdl2).What method can I use ?

Regards

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by John Hunsley -

Hi, the operation you are looking for is get_role_byid   or get_role_byname

In reply to John Hunsley

Re: OKTech Web Services

by snadly Mohamed Amine -

hi, thanks for the replay

well get_role_byid and get_role_byname doesn't return the role of a specific user, instead it return the role record of a specific role .

But I solved the problem by parsing the userRecord and retreiving the role field value .

 

Cheers

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by Patrick Pollet -

Yes, this is the easiest way. A raw value of role field (1=admin,2=creator, 3=teacher, 4=nonediting, 5=student....) has been added to simplify clients codes to all get_user(s) operations.  It does not take care of extra capabilities that may have been added locally to some context within the target course

The 'official way' is to call has_role_in_course() ...but at the cost of one more SOAP call.

 

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

hi patrick,

Why the roleid field in a user record always =0, this doesn't help.

Is there a way to make this raw field change in dependce with the user nature?

Any idea?

Is thre a settings up I need to do first when asseigning a role to an user in moodle?

regards

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by snadly Mohamed Amine -

hi ,

something is wrong with the field "role" in UserRecord , no matter what I do , it always returns 0 as value.

It supposes return 3 for teacher and 5 for student and 1 for manager,...

regards

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by snadly Mohamed Amine -

hi again ,

I ve been trying for 5 hours to find a way to retreive the role depending on parameters of a specific user using the okteck web services methods, but no luck so far

I need the role retreived in back office after the authentication , so i can manage the redirection toward the UIs. If the authenticated user is a teacher , then he will be redirected toward a specific UI.And to a diffrent UI in case he is a student . This is extremely important in a moodle client application.

I even tried to create a web service but I am just not good at it .

Please help me with this issue

Regards

In reply to snadly Mohamed Amine

Re: OKTech Web Services

by Patrick Pollet -

It does not work that way. An user can be a teacher in one course and a student in another one, so you cannot retrieve a role based only on that user 'login'., you must provide also the target course.  In old Moodle there was a function is_teacher_isanycourse but it is now deprecated, so was not implemented in Web Service

 

You must either call :

  • get_my_courses, then for each course the field myrole in each returned courseRecord will contains 1,2,...6, thus giving the 'primary' role of that user in that course.
  • get_course_users , then for a given course you will get the list of 'enroled people' and for each of them the field role with be 1,2,3...
  • get_primary_role_incourse , then for a given user and a given course it will return the minimal value of all roles he may have in that course (thus the primary name) : i.e. if admin 1, teacher 3 ....
  • has_role_in_course , then for a given user, a given course  and a given role id (1...6) it will return true or false
  • any other call related to users will return 0 in role field

Cheers.

Edit : the two calls get_primary_role_incourse and has_role_incourse were not present in the new WSDL emitted, so could not be called with the new method via wspp/wsdl_pp2.php ; they were OK with the old one wspp/wsdl_pp.php

They just have been added in the last commit on github for moodlews and also to the jar needed from Ksoap2 (checkout moodlews_1.8.2.jar on github for moodlews_ksoap2).

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

Hi patrick,

sorry for disturbing you but i need your help

I found the "get-resources" method that returns all the resources of a specific courses i think , but I did not understand the "idfield" field.

would you tell me what does it represent ?

 

Regards

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

Hi patrick

how can I retreive the files list of a specefic course using the oktech web services.

For exemple I created a course named "Java" and two pdf files under it .I want to get these files.

Regards

In reply to Patrick Pollet

Re: OKTech Web Services

by Giulio Valente -

Hi Patrick,

Do you know if it is possible to use OKTech with Shibboleth? And how to set up a proper login with it?

Thank you.

-Giulio

In reply to Giulio Valente

Re: OKTech Web Services

by Patrick Pollet -

Definitively not working with Shibboleth nor CAS. The login process expects an 'internal' authentification method such as manual, ldap, external DB or even dedicated web service  ... where login & pwd can be internally checked for match in a simple php script. But no way with some systems that may redirect to another Web page such as CAS or Shibboleth.

 

I double checked source code (see login method in script server.class.php)  and currently all auth plugins classes located in Moodle's auth/ directory that return false to is_internal() method will be rejected.

Cheers.

 

NB : Moodle 2.0 WS may works with Sibboleth/CAS since it has an alternate authentication process using a token that I don't not about...

In reply to Patrick Pollet

Re: OKTech Web Services

by Patrick Pollet -

Hello,

I finally found some time to update the documentation of OK Tech both on Moodle docs and on github project associated Wiki. Featured page for today is https://github.com/patrickpollet/moodlews/wiki/Extending-the-moodle-ws that's try to explain how to add new operations to this Web Service . The example given in that tutorial (i.e. adding a get_message_contacts operation the esay way) is purely for demonstration since that operation sending back all contacts of a Moodle's user (with message counts and online status) has just been added to the latest commit. Special delivery for John H. that may need it wink

 

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by Giulio Valente -

Hi Patrick,

thank for your answer.... it was a bad news for me :P

I'm creating a moodle client for my school. Since here in Switzerland all the university use moodle with a centralized login to shibboleth.

Anyway the first version of this client should use the normal login. But I have to developed it considering that will be extended to use a login with shibboleth.

Now I'm looking for two ways, maybe you can give me some suggestions:

1.Using the OKTech services for the first version. Then for the shibboleth modifying the login of the plugin such that will work with the internal authentication of shibboleth.  Is this a possible solution on your advice?

2.Extend the MoodleRest Library with the necessary services (maybe the same as in OKTech plugin). For this solution I did some research but I didn't found any ws different from the default ones. The problem is this could take long time and I really don't I to start it: login, maintain the session. Is this a valid solution, where could I find some services (such the login) that have already been implemented? Could I take maybe the services (the structure) from OKTech?

Thank you very much

In reply to Giulio Valente

Re: OKTech Web Services

by Patrick Pollet -

Hi Guilio,

I think you could modify OK Tech login operation or better  add a new operation loginShibo that will do the job. As long as it returns a valid client number and a session key (and inject it it the table mdl_webservices_session) for later use by all other operations., that is change the beginning of current operation 'login' but keep the second part that deals with the database tables. (ie the par that start at the comment ' /// Verify that an active session does not already exist for this user. ...'

- the only trouble I see is how this operation will invoke the external server that holds Shiboleth  data (ie launch some sort of Web browser ?) . I have no experience in Shiboleth ... but if it is like CAS we use here, I guess you will have to have some 'sort of cookie' on the client side that states that authentification has been successul sometime before ; that is you must force your future clients to first connect to Shiboleth, and keeps the tokens to sent it to the operation 'loginShibo'... that will check that the tokens are still valids ...(maybe an extra table in the data base ? ).

Alternatively you may consider adding a new authentication plugin to Moodle and use it to 'login' with the credentials returned by Shiboleth...

I don't know if using/extending  MoodleRest library will make any difference in that matter.

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by Esteban Chamba Jimenez -
Hello .. I am getting an error when I try to run "php genwsdl.php" I do this: "C: \ xampp \ php> php C: \ xampp \ htdocs \ mymoodle \ WSPP \ genwsdl.php" and get the following error: "Fatal error: requiere_once (): Failed opening required '.. / config.php' (include_path = '.; \ xampp \ php \ PEAR)" .. maybe someone knows how to solve, or what is the correct way to do this
In reply to Esteban Chamba Jimenez

Re: OKTech Web Services

by Patrick Pollet -

Hi

1) the script genwsdl.php is meant to regenerate the provided WSDL if you plan to EXTEND the Web Service, i.e. to add operations. See https://github.com/patrickpollet/moodlews/wiki/Extending-the-moodle-ws

Otherwise you don't need to reun in to 'install' and 'use ' OK Tech WS;

2) If you must run it, you must be into the wspp directory and simply run 'php genwsdl.php'.

 

Cheers

In reply to Justin Filip

Re: OKTech Web Services

by John Hunsley -

Hi, I have successfully created an Android app which makes use of the OKTech Web Services plug-in.

 

There are 3 projects which you will need to build, the Core and the OKTech client do the backend work and act as a client to the web serivce end point. The Android Messenger is a messaging app which works just like Sms using the Moodle Messgaing functionality.

 

All my work is open source and on GitHub, please feel free to contribute and use my code as you see fit.

 

https://github.com/johnhunsley

 

The README.txt in the Messenger project is pretty comprehensive, covers everything you need to successfully build the Android app and get it branded and on the market but if you need further help please contact me.

 

Kind regards,

 

John

In reply to John Hunsley

OKTech Web Services is going REST

by Patrick Pollet -

Hello,

I am pleased to announce that I just commited on github project's page https://github.com/patrickpollet/moodlews revision 1.8.5 that now support also the REST protocol, in addition to the historical SOAP protocol, thus allowing writing of more potential clients. I am obviously targetting iPhones and others where java (and its rich set of SOAP aware libraries) is not the 'favourite language'.

In REST mode, the main entry point is http://yourmoodle/wspp/service_pp2.php and expects at least two parameters (POST for real stuff or GET in testing mode) named wsfunction (the name of the target operation) and wsformatout (the output format desired). Others parameters specific to the supported target operation are the same as in SOAP mode.

Currently all operations described in the WSDL are supported.  Although the usual workflow (i.e : call to login (username,password), fetch the client and session key, passing them as arguments of the target operation and finally logout) , is stille the recommanded one for real clients, there is also a singleshot mode if two parameters wsusername and wspassword are detected, thus allowing to test directly an operation (in one shot wink

Supported output formats are :

  • json : suitable for many parsing libraries such as Google's Gson or Ajax clients
  • php : the results are serialized using php standard function serialize() and should be deserialized on the client side by the standard php function unserialize()
  • xml : we use the same XML format as Moodle 2.0's official Web Service, so parsing routines of existing clients can be reused
  • dump : a simple crudely formatted text dump of the returned data (for debugging/data analyzing  purposes)

See Moodle's docs page http://docs.moodle.org/en/Web_Services:OK_Tech_Web_Services of this projet for examples of usage .

A new project has been launched on github to automatically create java stub and helper classes suitable for usage in REST mode, with JSON output format.

See https://github.com/patrickpollet/moodlews_gson

Enjoy.

Edit : The REST part should be considered as pré-beta version, and will be finalized when more testings/feedbacks are done by the community.

In reply to Patrick Pollet

Re: OKTech Web Services is going REST

by Giulio Valente -

Hi,

Thank you for your great job. I will try on my android client asap, maybe it will be faster smile

I'm having some problems with get_my_courses:

I get all the informations but when I try to get_students or get_teachers/get_teacher it returns only an empty string.

It is normal?

Another question:

I'm still having trouble with the calendar:

get_events(MoodleWSDL.getCLIENT(), MoodleWSDL.getSESSIONKEY(), 0, "id""") is the only way to get all the events....

The other combinations does not work.

Thank you for the support

-Giulio

In reply to Giulio Valente

Re: OKTech Web Services is going REST

by Giulio Valente -

Hi Patrick,

Sorry but I have another question for you smile

I'm trying to get the resource informations from the courses, I tried in the following two ways:

get_resourcefile_byid(MoodleWSDL.getCLIENT(), MoodleWSDL.getSESSIONKEY(), 3);

get_resources(MoodleWSDL.getCLIENT(), MoodleWSDL.getSESSIONKEY(), new String[]{"1"}, "id");

And I always get:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>Wspp Server</faultcode><faultstring>feature get_resources for Moodle 2.0 not yet implemented</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>

Is there any way to download resources like .pdf, .doc,... ?

It is a really important features for my project.

Thank you

-Giulio

 

In reply to Giulio Valente

Re: OKTech Web Services is going REST

by Patrick Pollet -

@Guilio,

get_students and get_teachers were broken last week . they should be OK is the latest commit. You can test them in 'singleshot' REST mode by

http://yourmoodle/wspp/service_pp2.php?wsusername=you&wspassword=yourpassword&wsformatout=dump&wsfunction=get_teachers&idcourse=116&idfield=id

 

or

http://yourmoodle/wspp/service_pp2.php?wsusername=you&wspassword=yourpassword&wsformatout=dump&wsfunction=get_students&idcourse=116&idfield=id

 

As far as get_events is concerned you send the parameters the wrong way. The value must be before the idfield so

something like get_events(MoodleWSDL.getCLIENT(), MoodleWSDL.getSESSIONKEY(), 8, themoodleid"id")  should work :

eg, still in REST

http://localhost/moodle.195/wspp/service_pp2.php?wsusername=xxxxx&wspassword=zzzzz&wsformatout=dump&wsfunction=get_events&eventtype=8&ownerid=ppollet&owneridfield=username

 

As far as get_resources is concerned, well ...   I need time and/or help of people more familiar than me to the new Moodle 2.0 files API to finish it ....

 

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services is going REST

by Giulio Valente -

Hi Patrick,

I'm testing my android client with the rest library and it works like a charm smile It's seems to be faster smile Also the link to test it, get_students and get_teachers work without problems

My question was about get_my_courses form the returns item I try to get the teacher directly from the record: ie.: returnedRecord.get_teacher/get_students but are all empty.

To get the teacher should I do another query with get_teachers from the moodle object? I think this will require an extra time :/

I'm still having also problem with get_events I tried with the rest link and it doesn't work.... maybe I didn't get what the ownerid is:

I tried with:

http://localhost:8888/wspp/service_pp2.php?wsusername=armando&wspassword=xxxxx&wsformatout=dump&wsfunction=get_events&eventtype=8&ownerid=armando&owneridfield=username

But I got only this:

Array
(
    [0] => stdClass Object
        (
            [error] => no results.
        )

)
)

While with 0,3,5,6,7 I get all the events....

Thank you very much for your help smile

In reply to Patrick Pollet

Re: OKTech Web Services is going REST

by Giulio Valente -

Hi Patrick,

I would like to ask you how is going with the get_resource method and if it will be possible to downloads the resources using moodle 2.0 soon.

Hope you have good news.

Thank you

-Giulio

In reply to Patrick Pollet

Re: OKTech Web Services is going REST

by Giulio Valente -

Hi Patrick,

I'm having some problems with get_my_assignment_grade function,

I get this error:

<faultstring>Wspp Base Server :activity assignment with id  unknown.</faultstring>

</SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>

and as parameter I give client, session key and the assignment id.

While with get_all_assignments all the assignments with grade 100 and no feedback.

I'm interested to get the grade and feedback of each assignment/activity.

Do you have any suggestion on how should I modify the php to get that informations?

Thank you very much.

In reply to Justin Filip

Re: OKTech Web Services

by Heiko Schach -

Hello,

I have been following the development of OK Tech Web Services and Moodle's core Web Services.
http://docs.moodle.org/en/Web_Services:OK_Tech_Web_Services
http://docs.moodle.org/en/Development:Web_services

Are there any plans to implement OK Tech Web Services operations using the Moodle 2 Web Services infrastructure?
We are at the moment looking into ways to integrate Moodle 2.x with our external Student Information System.
The Moodle 2 core Web Services infrastructure looks promising but it's still lacking the functionality we need. Would be great to see OKTech WS's functionality available in Moodle 2.x core Web Services.

regards,
Heiko

In reply to Heiko Schach

Re: OKTech Web Services

by Patrick Pollet -

@Heiko,

After some exchanges with Moodle HQ, here is my best answer : http://docs.moodle.org/en/Web_Services:OK_Tech_Web_Services#The_future

Cheers.

In reply to Patrick Pollet

Re: OKTech Web Services

by snadly Mohamed Amine -

hi patrick

I tried the message_send() with soapui , and in spite of the response 'could not iniciate mail fonction' , the message is sent , and i can check it in moodle . So i tried to implement this fuction in my application. But something is wrong , a classcast exception (moodle_soapserverBindingStub class) is thrown wen I call the message_send web service.

here is my code :

Mdl_soapserverBindingStub moodle_msg = new Mdl_soapserverBindingStub(recup_url,recup_namespace,WS_DEBUG);

moodle_msg.message_send(recup_id, recup_sessionkey,"3","id","hello");

Any ideas ?

regards

In reply to Patrick Pollet

Re: OKTech Web Services

by Patrick Pollet -

Hello,

I am excited to announce that OK Tech WS can now be used also under the official Moodle 2.0 infrastructure. You may now still use it either the 'historical way' or the Moodle 2.0 way.

This has been committed as an alpha version of github starting at https://github.com/patrickpollet/moodlews/commit/d5349f2db42d570579a9ead201d0a923f04f6967

See the README file in wspp/moodle2integration folder.

Enjoy.

In reply to Justin Filip

Preserving Grades for "Unenrolled" Students

by Art Shelly -

My current project involves synchronizing our university’s SIS course enrollment information with Moodle 2.0.3+ using OKTech web service’s API.  Should a student withdraw from a course I would like to preserve the teacher’s ability to view the corresponding student’s grade information in Moodle.

Invoking the web service method “remove_user_from_course” has the unfortunate consequence of not only deleting the student from the course but also all of their grade information.

Moodle 2.0’s UI has the ability, under the “Enrolment methods” column of the “Enrolled” users’ page for the course to change a student’s enrolment from “Active” to “Suspended”.  This appears to have exactly the desired result – their grades are kept, their name is flagged as suspended in the grade book, and the student no longer can access the course.  The page's php code can be found in enrol/users.php under the "edit" action.

Questions:
#1  Can the web services API be used to suspend a user from a course?
#2  If not, can this behavior be automated by some other mechanism?
#3  Or is there a better way, other than suspension, to accomplish this same result?

 

 

In reply to Art Shelly

Re: Preserving Grades for "Unenrolled" Students

by Patrick Pollet -

Hello,


>#1  Can the web services API be used to suspend a user from a course?

No. Current API is mostly based on Moodle 1.9 behavior and 'suspsenion' of users enrolments only appeared in 2.0

>#2  If not, can this behavior be automated by some other mechanism?

I suspect that you will have to extend the WS to add a couple operations such as suspend_user_enrolment ($client,$sesskey,$userid,$useridfield,$courseid,$courseidfield,$enrolmethod) and the corresponding resume_user_enrolment.

something like $moodle->suspend_user_enrolment ($client,$sesskey,'jdoe','username','chem101','idnumber','manual')

In final this operation should

1) check moodle version >=2.0 by peeking at $CFG->wspp_using_moodle20 flag that is automatically set upon OKTech inilitialzation code

2) check/retrieve as usual $user and $course from ($userid,$useridfield) and ($courseid,$courseidfield) ; I just noticed that remove_user_from_course does not have the '$*idfields' extra parameters and expect simple Moodle user id and course id, so you could just do the same...

2bis) check logged user capability to enrol/unenrol in that course

Actually almost the same code as remove_user_from_course

3) look into mdl_enrol table for the $enrolid of the given $enrolmethod for the $course->id and if found use ( $enrolid, $user->id) to update the status field of the corresponding record in table mdl_user_enrolments to 1 if suspended of 0 if not...

I guess it should be quite easy to implement (see https://github.com/patrickpollet/moodlews/wiki/Extending-the-moodle-ws)

I do hope that the get_grades operations, that relies on API function grade_get_course_grade will then honor this 'suspension'.

>#3  Or is there a better way, other than suspension, to accomplish this same result?

Maybe your application could simply keep track of suspended users (and thus not call oktech remove_user_from_course operation) and filter them off when retrieving their grades from subsequent oktech calls to get_course_grades or get_user_grades

Cheers.

In reply to Patrick Pollet

Re: Preserving Grades for "Unenrolled" Students

by Catalin Maican -

Patrick,

i've seen here: https://github.com/patrickpollet/moodlews/blob/master/wspp/moodlewsdl.xml

that you added support for getting resource, even downloading file content I presume (via get_resourcefile_byid, get_resources, get_instances_bytype and other operations)

Now, is it possible somehow to "add" a resource to a course ?

Thanks,
Catalin

In reply to Catalin Maican

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

hi,

i'm a newbie, i would like to make  a client android using moodle's web service.

i've download https://github.com/patrickpollet/moodlews and   i've installed moodle 2.0.

i tried to follow the file's instruction ISTALL.txt but i have some problem when i try to run the script :php wsdl2php.php http://yourmoodle/wspp/wsdl_pp.php

the problem is:

PHP warning: unable to load dynamic library 'C:\php\ext\php_java.dll'

the specified procedure could not be found

so i've installed zend server with java bridge to solve this problem but it still remains.

another thing i try lo run login request with soapUI.... but i received this response:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>MOODLE:error</faultcode>
         <faultstring>Wspp Base Server :Invalid username and / or password.</faultstring>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

 

so which username/ password i have to fill in??

thanks in advance and sorry for my poor english!!!

 

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

hi patrick,

i tried to make an android client that uses moodle's web service but i have this error:

org.xmlpull.v1.XmlPullParserException: expected: START_TAG".

my code is:

package com.log;

import android.app.Activity;
import android.os.Bundle;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


public class log extends Activity {
   
private static final String SOAP_ACTION = "http://192.168.1.3/moodle/wspp/wsdl#login";

private static final String OPERATION_NAME = "login";

private static final String WSDL_TARGET_NAMESPACE = "http://192.168.1.3/moodle/wspp/wsdl";

private static final String SOAP_ADDRESS = "http://192.168.1.3/moodle/wspp/login.asmx";

@Override
public void onCreate(Bundle savedInstanceState)  {
super.onCreate(savedInstanceState);

TextView textView = new TextView(this);

setContentView(textView);

SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
request.addProperty("username", "admin");
request.addProperty("password", "Riccardo_1980");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.bodyOut=request;

HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

try

{

httpTransport.call(SOAP_ACTION, envelope);

Object response = envelope.getResponse();

textView.setText(response.toString());

}



catch (Exception exception)

{

textView.setText(exception.toString());

}


}
}

 

please help me... i have no idea to solve the problem!!!!thank you in advance

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by Patrick Pollet -

@rick, 

at least your  SOAP_ADDRESS = "http://192.168.1.3/moodle/wspp/login.asmx"; is definitively wrong.

Please do not waste your time rewriting all basic operations using ksoap2 low level functions. Just decide whether you want to talk SOAP or REST and use higher level API described at https://github.com/patrickpollet/moodlews_ksoap2 or https://github.com/patrickpollet/moodlews_gson 

In the first case you will need ksoap2  jar and in the second Google gson jar.

An example of SOAP Android client is given here https://github.com/patrickpollet/moodlews_ksoap2/blob/master/src/net/patrickpollet/moodleandroid/moodleandroid2.java

 

More exhaustive examples in both SOAP and REST are given in classes named Testx.java  that do not run on Android but can be usd as samples of what can be done.

 

Cheers.

In reply to Patrick Pollet

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

Hi Patrick thank you so much...

i rewrite the code and i substitute the row :

SOAP_ADDRESS = "http://192.168.1.3/moodle/wspp/login.asmx

with the following

private static final String SOAP_ACTION = "http://192.168.1.3/moodle/wspp/wsdl";

private static final String OPERATION_NAME = "login";

private static final String WSDL_TARGET_NAMESPACE = "http://192.168.1.3/moodle/wspp/wsdl";

private static final String SOAP_ADDRESS = "http://192.168.1.3/moodle/wspp/service_pp2.php";

but i have the same errors...

i'm a newbie in android (and moodle) and i try to understand how does it works using web services and ksoap2 library...

i tried https://github.com/patrickpollet/moodlews_ksoap2/blob/master/src/net/patrickpollet/moodleandroid/moodleandroid2.java

i build the android project with the ksoap2 jar and it works and i've seen the phrase 'hello world,moodle' but i don't understand very much how it works...

in the code:

private final String MOODLE_URL = "http://192.168.1.3/moodle";
    private final String LOGIN = "ciao";
    private final String PWD = "Riccardo_1980";
    private final boolean WS_DEBUG = false;

i put a wrong login but i have the same response, i've seen already 'hello world,moodle'...so this script don't try to connect with the moodle's db??

another thing: if i would test a web service function like "get_my_courses"  what kind a script have I to write??? i have to import ksoap2 library and define this variables

private static final String SOAP_ACTION = "http://192.168.1.3/moodle/wspp/wsdl";

private static final String OPERATION_NAME = "get_my_courses";

private static final String WSDL_TARGET_NAMESPACE = "http://192.168.1.3/moodle/wspp/wsdl";

private static final String SOAP_ADDRESS = "http://192.168.1.3/moodle/wspp/service_pp2.php";

i have very confused idea so please help me!! thank you so much

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by Patrick Pollet -

>i put a wrong login but i have the same response, i've seen already 'hello >world,moodle'...so this script don't try to connect with the moodle's db??

 

as stated on the comment at the top of the sample code, the program does not display anything on the Android device but write all data exchanged in the device system log.

So under Eclipse, open the DDMS perspective and consult the Log cat . You will see there all output of the code .

>another thing: if i would test a web service function like "get_my_courses"  what >kind a script have I to write??? i have to import ksoap2 library and define this >variables

 

the sample code provided just does this. it call first login, the get_my_id then get_my_courses

see

CourseRecord[] crs = moodle.get_my_courses(lr.getClient(),lr.getSessionkey(),""+me,"");
Cheers.

In reply to Patrick Pollet

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

hi Patrick,

thank you so much!

i run login script and i see the Logcat and this is what i've received:

 

09-29 21:05:09.785: INFO/ActivityManager(52): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.moodle/.moodle }
09-29 21:05:10.155: INFO/ActivityManager(52): Start proc com.moodle for activity com.moodle/.moodle: pid=232 uid=10026 gids={3003, 1015}
09-29 21:05:10.165: INFO/ActivityManager(52): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.moodle/.moodle }
09-29 21:05:10.365: INFO/jdwp(232): received file descriptor 20 from ADB
09-29 21:05:10.505: DEBUG/ddm-heap(232): Got feature list request
09-29 21:05:10.655: DEBUG/dalvikvm(52): GREF has increased to 301
09-29 21:05:11.235: WARN/System.err(232): org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <html>@2:7 in java.io.InputStreamReader@43779e68)
09-29 21:05:11.255: WARN/System.err(232):     at org.kxml2.io.KXmlParser.exception(KXmlParser.java:245)
09-29 21:05:11.255: WARN/System.err(232):     at org.kxml2.io.KXmlParser.require(KXmlParser.java:1376)
09-29 21:05:11.265: WARN/System.err(232):     at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:127)
09-29 21:05:11.265: WARN/System.err(232):     at org.ksoap2.transport.Transport.parseResponse(Transport.java:63)
09-29 21:05:11.265: WARN/System.err(232):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
09-29 21:05:11.265: WARN/System.err(232):     at net.patrickpollet.moodlewsold.core.MoodleWSBindingStub.login(MoodleWSBindingStub.java:31)
09-29 21:05:11.275: WARN/System.err(232):     at com.moodle.moodle.onCreate(moodle.java:58)
09-29 21:05:11.275: WARN/System.err(232):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
09-29 21:05:11.275: WARN/System.err(232):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
09-29 21:05:11.285: WARN/System.err(232):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
09-29 21:05:11.285: WARN/System.err(232):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
09-29 21:05:11.285: WARN/System.err(232):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
09-29 21:05:11.285: WARN/System.err(232):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 21:05:11.295: WARN/System.err(232):     at android.os.Looper.loop(Looper.java:123)
09-29 21:05:11.295: WARN/System.err(232):     at android.app.ActivityThread.main(ActivityThread.java:4203)
09-29 21:05:11.295: WARN/System.err(232):     at java.lang.reflect.Method.invokeNative(Native Method)
09-29 21:05:11.295: WARN/System.err(232):     at java.lang.reflect.Method.invoke(Method.java:521)
09-29 21:05:11.305: WARN/System.err(232):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-29 21:05:11.305: WARN/System.err(232):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
09-29 21:05:11.305: WARN/System.err(232):     at dalvik.system.NativeStart.main(Native Method)
09-29 21:05:11.605: INFO/ActivityManager(52): Displayed activity com.moodle/.moodle: 1755 ms (total 1755 ms)

so i have the same problem : org.xmlpull.v1.XmlPullParserException: expected: START_TAG

do you have any idea to solve this problem?? what is the cause of this error?

thank you so much!!

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by Patrick Pollet -

@rick,

 

: org.xmlpull.v1.XmlPullParserException: expected: START_TAG means that the Moodle part of OKTech WS did not answered by a well formed XML document as expected. So I suspect some installation problem. Did you visit notifications in Moodle adminstration after installing it ????

 

you can test by directly calling it with a browser : 

http://youmoodleserver/wspp/wsdl_pp2.php should returns you a well formed XML document detailing the WSDL of the operations and exchanged data types. I suspect that you get something else (an error message, a php notice or just nothing it the script died....). Also try to put your Moodle in full debugging mode (in Administrative screens) to get more detailed error reporting.  

also try http://yourmoodleserver/wspp/service_pp2.php that should returns you the list of available operations 

Plz also check the file moodledata/debug.out that contains a lot of debugging informations specific to the server part.

 

When all this works as expected you can read the documentation of current operations (names and required parameters) at 

http://prope.insa-lyon.fr/~ppollet/moodlews/java/ksoap2/moodlews/net/patrickpollet/moodlews/core/Mdl_soapserverBindingStub.html

and experiment with then with an interactive SOAP client such as SoapUI.

 

Cheers.

 

 

In reply to Patrick Pollet

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

Hi Patrick,

i visited notification and this is the response at cron.php script

Server Time: Fri, 30 Sep 2011 16:08:48 +0200


Cleaning up stale sessions
Starting activity modules
Processing module function assignment_cron ...... used 3 dbqueries
... used 0.18111300468445 seconds
done.
Processing module function chat_cron ...... used 5 dbqueries
... used 0.16782116889954 seconds
done.
Processing module function forum_cron ...Starting digest processing...
Cleaned old digest records
Removing old forum read tracking info...
... used 7 dbqueries
... used 0.25402498245239 seconds
done.
Processing module function scorm_cron ...Updating scorm packages which require daily update
... used 5 dbqueries
... used 0.069554090499878 seconds
done.
Finished activity modules
Starting blocks
Processing cron function for rss_client....
0 feeds refreshed (took 0.051905 seconds)
done.
Finished blocks
Starting quiz reports
Processing quiz report cron function quiz_report_statistics_cron ...... used 3 dbqueries
... used 0.034582853317261 seconds
done.
Finished quiz reports
Starting admin reports
Finished admin reports
Starting main gradebook job ...
done.
Starting processing the event queue...
done.
Checking automated backup status...INACTIVE
Running auth crons if required...
Running enrol crons if required...
Running cron for enrol_self...
Running cron for enrol_cohort...
Starting course reports
Finished course reports
Starting gradebook plugins
Finished gradebook plugins
Fetching external blog entries...done.
Deleting blog associations linked to non-existent contexts...done.
Starting registration update on hubs...
XML-RPC must be enabled in order to update the registration.
Finished registration update on hubs.
Deleting old draft files... done.
Cleaning up files from deleted contexts... done.
Deleting trash files... done.
Deleting session linked tokens more than one day old...done.
Processing customized cron scripts ...done.
Cron script completed correctly
Execution took 3.806234 seconds

i think that the problem maybe is here:

XML-RPC must be enabled in order to update the registration.

what do you think about?
now i try yours other suggestions
In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

another thing in moodledata's folder there isn't debug.out file , why? when i've installed moodle i hadn't any problem...

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

.....another thing..i've install php_xmlrpc ext so now when i try to run the appl i have this error :

 

09-30 16:07:52.119: WARN/System.err(747): org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <html dir='ltr' lang='en' {http://www.w3.org/XML/1998/namespace}xml:lang='en'>@2:79 in java.io.InputStreamReader@435bc330)

i don't understand

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

i think that there is a conflict with the url page within the android's browser...if i put manually the url 192.168.1.3:100/moodle in the android's browser it not works but with 192.168.1.3:100/moodle/wspp it shows me the directory but if i try  192.168.1.3:100/moodle/wspp/service_pp2.php it crushes...i dont have any idea please help

In reply to ricky farris

Re: Preserving Grades for "Unenrolled" Students

by Patrick Pollet -

so it proves that the server part is not well installed. This file will be created at the first successfull call. 

what gives Firefox or IE when you call http://youmoodleserveraddress/wspp/wsdl_pp2.php ? 

In reply to Patrick Pollet

Re: Preserving Grades for "Unenrolled" Students

by ricky farris -

when i call localhost:100/moodle//wspp/wsdl_pp2.php i received a file called moodlews2.wsdl so i think that it's working but if i try to run the login script under eclipse it doesn't work.... i don't understand... i think that there is a problem parsing xml...but i don't know why?? maybe the problem is in the url or in the namespace.... my script is the following

 

package com.log;

import android.app.Activity;
import android.os.Bundle;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


public class log extends Activity {
   
private static final String SOAP_ACTION = "http://192.168.1.3:100/moodle/wspp/wsdl2/login";

private static final String OPERATION_NAME = "login";

private static final String WSDL_TARGET_NAMESPACE = "http://192.168.1.3:100/moodle/wspp/wsdl2/";

private static final String SOAP_ADDRESS = "http://192.168.1.3:100/moodle/wspp/service_pp2.php";

@Override
public void onCreate(Bundle savedInstanceState)  {
super.onCreate(savedInstanceState);

TextView textView = new TextView(this);

setContentView(textView);

SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
request.addProperty("username", "admin");
request.addProperty("password", "Riccardo_1980");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.bodyOut=request;

HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

try

{

httpTransport.call(SOAP_ACTION, envelope);

Object response = envelope.getResponse();

textView.setText(response.toString());
textView.setText("welcome"+response.toString());
}



catch (Exception exception)

{

textView.setText(exception.toString());

}


}
}

 

i'm really confused and sad plz help me!!thank you

In reply to Justin Filip

Using get_activities()

by Scott Hooper -

I have a project that uses OKTech WS extensively and for the most part everything is working beautifully. I have run into a problem though with get_activities. Here's the code I'm using:

Dim act As New MoodleWS.getActivitiesReturn
act = moodle.get_activities(lr.client, lr.sessionkey, "1138", "id", "125", "id", 50)

 

I have verified that the hardcoded values in the above relate to a valid student and course. Upon executing the above i get the following error:

 


The content type application/xml of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body><SOAP-ENV:Fault>
<faultcode>MOODLE:error</faultcode>
<faultstring>Error reading from database - ERROR: function from_unixtime(bigint, unknown) does not exist at character 110
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

SELECT l.*,u.auth,u.firstname,u.lastname,u.email,
u.firstaccess, u.lastaccess, u.lastlogin, u.currentlogin,
FROM_UNIXTIME(l.time,'%%d/%%m/%%Y %%H:%%i:%%s' )as DATE,
FROM_UNIXTIME(u.lastaccess,'%%d/%%m/%%Y %%H:%%i:%%s' )as DLA,
FROM_UNIXTIME(u.firstaccess,'%%d/%%m/%%Y %%H:%%i:%%s' )as DFA,
FROM_UNIXTIME(u.lastlogin,'%%d/%%m/%%Y %%H:%%i:%%s' )as DLL,
FROM_UNIXTIME(u.currentlogin,'%%d/%%m/%%Y %%H:%%i:%%s' )as DCL
FROM mdl_log l , mdl_user u
WHERE l.userid = u.id
AND u.id = 1137
AND l.course=125
ORDER BY l.time DESC LIMIT 50 OFFSET 0
[array (
)]</faultstring>
</SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:'.

 

The error seems to be indicating that the internal function call "from_unixtime(bigint, unknown)" is invalid. Does this mean there is a problem with OKTech or with our Moodle hosting environment?

In reply to Scott Hooper

Re: Using get_activities()

by Patrick Pollet -

Hello,

     I suspect that your underlying database is not 'MySQL' but Postgres or other, and unfortunately the function from_unixtime is mysql specific. see http://drupal.org/node/359777

the values DATE,DLA, DFA, DLL and DLC are an attempt to convert Unix time stamp to localized strings, easier to display on the client side .

A quick fix should be to edit function get_activities in script wspp/server.class.php as follow 

Replace 

SELECT l.*,u.auth,u.firstname,u.lastname,u.email,
u.firstaccess, u.lastaccess, u.lastlogin, u.currentlogin,
FROM_UNIXTIME(l.time,'$fmtdate' )as DATE,
FROM_UNIXTIME(u.lastaccess,'$fmtdate' )as DLA,
FROM_UNIXTIME(u.firstaccess,'$fmtdate' )as DFA,
FROM_UNIXTIME(u.lastlogin,'$fmtdate' )as DLL,
FROM_UNIXTIME(u.currentlogin,'$fmtdate' )as DCL
EOS;

by 

SELECT l.*,u.auth,u.firstname,u.lastname,u.email,
u.firstaccess, u.lastaccess, u.lastlogin, u.currentlogin,
0 as DATE,
0 as DLA,
0 as DFA,
0 as DLL,
0 as DCL
EOS;

This will returns 0 for these columns (that are required to be present for later SOAP encoding.)

Eventually also edit function filter_activity in filterlib.php by UNCOMMENTING the calculation of these values to read 

function filter_activity($client, $activity) {
    //add attributes with all timestamps converted to friendly dates
    //using moodlelib function userdate .
    /* some problems with a french Moodle and accentuaed month names
 they are returned in latin1 and not utF8 --> SOAP conversion error */
 $activity->DATE=userdate($activity->time);
 $activity->DLA=userdate($activity->lastaccess);
 $activity->DFA=userdate($activity->firstaccess);
 $activity->DLL=userdate($activity->lastlogin);
 $activity->DCL=userdate($activity->currentlogin);
    return $activity;
}

This may cause some SOAP encoding errors with some php versions were userdate returns month names in latin1 and not in utf8 . That's why I did these conversions in the SQL, forgetting that from_unixtime() is not an universal SQL function.

In that case, just leave filter_activity as it was and do the localisation on the client side from returned values present in  time, lastaccess, firstaccess, lastlogin and currentlogin ( they are all Unix time stamps). 

Cheers

 

In reply to Justin Filip

OKTech Web Services

by Archana Suresh -

I have a problem with using OKTech Web Services in my server. My moodle version is 2.3.1 and i have installed with latest version of wspp.

I have made database upgrade for the same and added the webreference http://moodle.build/wspp/wsdl_pp.php in my dot net application. While running the application, I am getting error following error message.

PHP Strict Standards: Declaration of mdl_baseserver::get_my_courses() should be
compatible with that of server::get_my_courses() in \moodle\wspp\mdl_baseserver.class.php on line 32 PHP Strict
Standards: Declaration of mdl_baseserver::affect_group_to_course() should be
compatible with that of server::affect_group_to_course() in \moodle\wspp\mdl_baseserver.class.php on line 32 PHP Strict
Standards: Declaration of mdl_baseserver::affect_grouping_to_course() should be
compatible with that of server::affect_grouping_to_course() in D:\School Of
PE\Moodle\Build\moodle\wspp\mdl_baseserver.class.php on line 32 PHP Strict
Standards: Declaration of mdl_baseserver::get_activities() should be compatible
with that of server::get_activities() in \moodle\wspp\mdl_baseserver.class.php on line 32 PHP Strict
Standards: Declaration of mdl_baseserver::affect_section_to_course() should be
compatible with that of server::affect_section_to_course() in \moodle\wspp\mdl_baseserver.class.php on line 32 PHP Strict
Standards: Declaration of mdl_baseserver::affect_users_to_cohort() should be
compatible with that of server::affect_users_to_cohort() in \moodle\wspp\mdl_baseserver.class.php on line 32 PHP Strict
Standards: Declaration of mdl_baseserver::affect_users_to_group() should be
compatible with that of server::affect_users_to_group() in \Moodle\Build\moodle\wspp\mdl_baseserver.class.php on line 32

 

Please advice.

In reply to Archana Suresh

Re: OKTech Web Services

by Mike Churchward -
Picture of Core developers Picture of Plugin developers Picture of Testers

I don't believe that code has ever been updated to work with Moodle 2. Moodle 2 has web services as part of its native code base, but they are not the same.

mike