lib.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Web services utility functions and classes
  18. *
  19. * @package core_webservice
  20. * @copyright 2009 Jerome Mouneyrac <jerome@moodle.com>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. require_once($CFG->libdir.'/externallib.php');
  24. /**
  25. * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
  26. */
  27. define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
  28. /**
  29. * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
  30. */
  31. define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
  32. /**
  33. * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
  34. */
  35. define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
  36. /**
  37. * General web service library
  38. *
  39. * @package core_webservice
  40. * @copyright 2010 Jerome Mouneyrac <jerome@moodle.com>
  41. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42. */
  43. class webservice {
  44. /**
  45. * Authenticate user (used by download/upload file scripts)
  46. *
  47. * @param string $token
  48. * @return array - contains the authenticated user, token and service objects
  49. */
  50. public function authenticate_user($token) {
  51. global $DB, $CFG;
  52. // web service must be enabled to use this script
  53. if (!$CFG->enablewebservices) {
  54. throw new webservice_access_exception('Web services are not enabled in Advanced features.');
  55. }
  56. // Obtain token record
  57. if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
  58. //client may want to display login form => moodle_exception
  59. throw new moodle_exception('invalidtoken', 'webservice');
  60. }
  61. $loginfaileddefaultparams = array(
  62. 'other' => array(
  63. 'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
  64. 'reason' => null,
  65. 'tokenid' => $token->id
  66. )
  67. );
  68. // Validate token date
  69. if ($token->validuntil and $token->validuntil < time()) {
  70. $params = $loginfaileddefaultparams;
  71. $params['other']['reason'] = 'token_expired';
  72. $event = \core\event\webservice_login_failed::create($params);
  73. $event->add_record_snapshot('external_tokens', $token);
  74. $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
  75. get_string('invalidtimedtoken', 'webservice'), 0));
  76. $event->trigger();
  77. $DB->delete_records('external_tokens', array('token' => $token->token));
  78. throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
  79. }
  80. // Check ip
  81. if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
  82. $params = $loginfaileddefaultparams;
  83. $params['other']['reason'] = 'ip_restricted';
  84. $event = \core\event\webservice_login_failed::create($params);
  85. $event->add_record_snapshot('external_tokens', $token);
  86. $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
  87. get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
  88. $event->trigger();
  89. throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
  90. . ' is not supported');
  91. }
  92. //retrieve user link to the token
  93. $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
  94. // let enrol plugins deal with new enrolments if necessary
  95. enrol_check_plugins($user);
  96. // setup user session to check capability
  97. \core\session\manager::set_user($user);
  98. //assumes that if sid is set then there must be a valid associated session no matter the token type
  99. if ($token->sid) {
  100. if (!\core\session\manager::session_exists($token->sid)) {
  101. $DB->delete_records('external_tokens', array('sid' => $token->sid));
  102. throw new webservice_access_exception('Invalid session based token - session not found or expired');
  103. }
  104. }
  105. //Non admin can not authenticate if maintenance mode
  106. $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
  107. if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
  108. //this is usually temporary, client want to implement code logic => moodle_exception
  109. throw new moodle_exception('sitemaintenance', 'admin');
  110. }
  111. //retrieve web service record
  112. $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
  113. if (empty($service)) {
  114. // will throw exception if no token found
  115. throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
  116. }
  117. //check if there is any required system capability
  118. if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
  119. throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
  120. }
  121. //specific checks related to user restricted service
  122. if ($service->restrictedusers) {
  123. $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
  124. if (empty($authoriseduser)) {
  125. throw new webservice_access_exception(
  126. 'The user is not allowed for this service. First you need to allow this user on the '
  127. . $service->name . '\'s allowed users administration page.');
  128. }
  129. if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
  130. throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
  131. }
  132. if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
  133. throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
  134. . ' is not supported - check this allowed user');
  135. }
  136. }
  137. //only confirmed user should be able to call web service
  138. if (empty($user->confirmed)) {
  139. $params = $loginfaileddefaultparams;
  140. $params['other']['reason'] = 'user_unconfirmed';
  141. $event = \core\event\webservice_login_failed::create($params);
  142. $event->add_record_snapshot('external_tokens', $token);
  143. $event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
  144. $event->trigger();
  145. throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
  146. }
  147. //check the user is suspended
  148. if (!empty($user->suspended)) {
  149. $params = $loginfaileddefaultparams;
  150. $params['other']['reason'] = 'user_suspended';
  151. $event = \core\event\webservice_login_failed::create($params);
  152. $event->add_record_snapshot('external_tokens', $token);
  153. $event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
  154. $event->trigger();
  155. throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
  156. }
  157. //check if the auth method is nologin (in this case refuse connection)
  158. if ($user->auth == 'nologin') {
  159. $params = $loginfaileddefaultparams;
  160. $params['other']['reason'] = 'nologin';
  161. $event = \core\event\webservice_login_failed::create($params);
  162. $event->add_record_snapshot('external_tokens', $token);
  163. $event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
  164. $event->trigger();
  165. throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
  166. }
  167. //Check if the user password is expired
  168. $auth = get_auth_plugin($user->auth);
  169. if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
  170. $days2expire = $auth->password_expire($user->username);
  171. if (intval($days2expire) < 0) {
  172. $params = $loginfaileddefaultparams;
  173. $params['other']['reason'] = 'password_expired';
  174. $event = \core\event\webservice_login_failed::create($params);
  175. $event->add_record_snapshot('external_tokens', $token);
  176. $event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
  177. $event->trigger();
  178. throw new moodle_exception('passwordisexpired', 'webservice');
  179. }
  180. }
  181. // log token access
  182. $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
  183. return array('user' => $user, 'token' => $token, 'service' => $service);
  184. }
  185. /**
  186. * Allow user to call a service
  187. *
  188. * @param stdClass $user a user
  189. */
  190. public function add_ws_authorised_user($user) {
  191. global $DB;
  192. $user->timecreated = time();
  193. $DB->insert_record('external_services_users', $user);
  194. }
  195. /**
  196. * Disallow a user to call a service
  197. *
  198. * @param stdClass $user a user
  199. * @param int $serviceid
  200. */
  201. public function remove_ws_authorised_user($user, $serviceid) {
  202. global $DB;
  203. $DB->delete_records('external_services_users',
  204. array('externalserviceid' => $serviceid, 'userid' => $user->id));
  205. }
  206. /**
  207. * Update allowed user settings (ip restriction, valid until...)
  208. *
  209. * @param stdClass $user
  210. */
  211. public function update_ws_authorised_user($user) {
  212. global $DB;
  213. $DB->update_record('external_services_users', $user);
  214. }
  215. /**
  216. * Return list of allowed users with their options (ip/timecreated / validuntil...)
  217. * for a given service
  218. *
  219. * @param int $serviceid the service id to search against
  220. * @return array $users
  221. */
  222. public function get_ws_authorised_users($serviceid) {
  223. global $DB, $CFG;
  224. $params = array($CFG->siteguest, $serviceid);
  225. $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
  226. u.lastname as lastname,
  227. esu.iprestriction as iprestriction, esu.validuntil as validuntil,
  228. esu.timecreated as timecreated
  229. FROM {user} u, {external_services_users} esu
  230. WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
  231. AND esu.userid = u.id
  232. AND esu.externalserviceid = ?";
  233. $users = $DB->get_records_sql($sql, $params);
  234. return $users;
  235. }
  236. /**
  237. * Return an authorised user with their options (ip/timecreated / validuntil...)
  238. *
  239. * @param int $serviceid the service id to search against
  240. * @param int $userid the user to search against
  241. * @return stdClass
  242. */
  243. public function get_ws_authorised_user($serviceid, $userid) {
  244. global $DB, $CFG;
  245. $params = array($CFG->siteguest, $serviceid, $userid);
  246. $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
  247. u.lastname as lastname,
  248. esu.iprestriction as iprestriction, esu.validuntil as validuntil,
  249. esu.timecreated as timecreated
  250. FROM {user} u, {external_services_users} esu
  251. WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
  252. AND esu.userid = u.id
  253. AND esu.externalserviceid = ?
  254. AND u.id = ?";
  255. $user = $DB->get_record_sql($sql, $params);
  256. return $user;
  257. }
  258. /**
  259. * Generate all tokens of a specific user
  260. *
  261. * @param int $userid user id
  262. */
  263. public function generate_user_ws_tokens($userid) {
  264. global $CFG, $DB;
  265. // generate a token for non admin if web service are enable and the user has the capability to create a token
  266. if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
  267. // for every service than the user is authorised on, create a token (if it doesn't already exist)
  268. // get all services which are set to all user (no restricted to specific users)
  269. $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
  270. $serviceidlist = array();
  271. foreach ($norestrictedservices as $service) {
  272. $serviceidlist[] = $service->id;
  273. }
  274. // get all services which are set to the current user (the current user is specified in the restricted user list)
  275. $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
  276. foreach ($servicesusers as $serviceuser) {
  277. if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
  278. $serviceidlist[] = $serviceuser->externalserviceid;
  279. }
  280. }
  281. // get all services which already have a token set for the current user
  282. $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
  283. $tokenizedservice = array();
  284. foreach ($usertokens as $token) {
  285. $tokenizedservice[] = $token->externalserviceid;
  286. }
  287. // create a token for the service which have no token already
  288. foreach ($serviceidlist as $serviceid) {
  289. if (!in_array($serviceid, $tokenizedservice)) {
  290. // create the token for this service
  291. $newtoken = new stdClass();
  292. $newtoken->token = md5(uniqid(rand(),1));
  293. // check that the user has capability on this service
  294. $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
  295. $newtoken->userid = $userid;
  296. $newtoken->externalserviceid = $serviceid;
  297. // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
  298. $newtoken->contextid = context_system::instance()->id;
  299. $newtoken->creatorid = $userid;
  300. $newtoken->timecreated = time();
  301. $DB->insert_record('external_tokens', $newtoken);
  302. }
  303. }
  304. }
  305. }
  306. /**
  307. * Return all tokens of a specific user
  308. * + the service state (enabled/disabled)
  309. * + the authorised user mode (restricted/not restricted)
  310. *
  311. * @param int $userid user id
  312. * @return array
  313. */
  314. public function get_user_ws_tokens($userid) {
  315. global $DB;
  316. //here retrieve token list (including linked users firstname/lastname and linked services name)
  317. $sql = "SELECT
  318. t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
  319. FROM
  320. {external_tokens} t, {user} u, {external_services} s
  321. WHERE
  322. t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
  323. $tokens = $DB->get_records_sql($sql, array( $userid));
  324. return $tokens;
  325. }
  326. /**
  327. * Return a token that has been created by the user (i.e. to created by an admin)
  328. * If no tokens exist an exception is thrown
  329. *
  330. * The returned value is a stdClass:
  331. * ->id token id
  332. * ->token
  333. * ->firstname user firstname
  334. * ->lastname
  335. * ->name service name
  336. *
  337. * @param int $userid user id
  338. * @param int $tokenid token id
  339. * @return stdClass
  340. */
  341. public function get_created_by_user_ws_token($userid, $tokenid) {
  342. global $DB;
  343. $sql = "SELECT
  344. t.id, t.token, u.firstname, u.lastname, s.name
  345. FROM
  346. {external_tokens} t, {user} u, {external_services} s
  347. WHERE
  348. t.creatorid=? AND t.id=? AND t.tokentype = "
  349. . EXTERNAL_TOKEN_PERMANENT
  350. . " AND s.id = t.externalserviceid AND t.userid = u.id";
  351. //must be the token creator
  352. $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
  353. return $token;
  354. }
  355. /**
  356. * Return a database token record for a token id
  357. *
  358. * @param int $tokenid token id
  359. * @return object token
  360. */
  361. public function get_token_by_id($tokenid) {
  362. global $DB;
  363. return $DB->get_record('external_tokens', array('id' => $tokenid));
  364. }
  365. /**
  366. * Delete a token
  367. *
  368. * @param int $tokenid token id
  369. */
  370. public function delete_user_ws_token($tokenid) {
  371. global $DB;
  372. $DB->delete_records('external_tokens', array('id'=>$tokenid));
  373. }
  374. /**
  375. * Delete a service
  376. * Also delete function references and authorised user references.
  377. *
  378. * @param int $serviceid service id
  379. */
  380. public function delete_service($serviceid) {
  381. global $DB;
  382. $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
  383. $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
  384. $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
  385. $DB->delete_records('external_services', array('id' => $serviceid));
  386. }
  387. /**
  388. * Get a full database token record for a given token value
  389. *
  390. * @param string $token
  391. * @throws moodle_exception if there is multiple result
  392. */
  393. public function get_user_ws_token($token) {
  394. global $DB;
  395. return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
  396. }
  397. /**
  398. * Get the functions list of a service list (by id)
  399. *
  400. * @param array $serviceids service ids
  401. * @return array of functions
  402. */
  403. public function get_external_functions($serviceids) {
  404. global $DB;
  405. if (!empty($serviceids)) {
  406. list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
  407. $sql = "SELECT f.*
  408. FROM {external_functions} f
  409. WHERE f.name IN (SELECT sf.functionname
  410. FROM {external_services_functions} sf
  411. WHERE sf.externalserviceid $serviceids)
  412. ORDER BY f.name ASC";
  413. $functions = $DB->get_records_sql($sql, $params);
  414. } else {
  415. $functions = array();
  416. }
  417. return $functions;
  418. }
  419. /**
  420. * Get the functions of a service list (by shortname). It can return only enabled functions if required.
  421. *
  422. * @param array $serviceshortnames service shortnames
  423. * @param bool $enabledonly if true then only return functions for services that have been enabled
  424. * @return array functions
  425. */
  426. public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
  427. global $DB;
  428. if (!empty($serviceshortnames)) {
  429. $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
  430. list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
  431. $sql = "SELECT f.*
  432. FROM {external_functions} f
  433. WHERE f.name IN (SELECT sf.functionname
  434. FROM {external_services_functions} sf, {external_services} s
  435. WHERE s.shortname $serviceshortnames
  436. AND sf.externalserviceid = s.id
  437. " . $enabledonlysql . ")";
  438. $functions = $DB->get_records_sql($sql, $params);
  439. } else {
  440. $functions = array();
  441. }
  442. return $functions;
  443. }
  444. /**
  445. * Get functions not included in a service
  446. *
  447. * @param int $serviceid service id
  448. * @return array functions
  449. */
  450. public function get_not_associated_external_functions($serviceid) {
  451. global $DB;
  452. $select = "name NOT IN (SELECT s.functionname
  453. FROM {external_services_functions} s
  454. WHERE s.externalserviceid = :sid
  455. )";
  456. $functions = $DB->get_records_select('external_functions',
  457. $select, array('sid' => $serviceid), 'name');
  458. return $functions;
  459. }
  460. /**
  461. * Get list of required capabilities of a service, sorted by functions
  462. * Example of returned value:
  463. * Array
  464. * (
  465. * [core_group_create_groups] => Array
  466. * (
  467. * [0] => moodle/course:managegroups
  468. * )
  469. *
  470. * [core_enrol_get_enrolled_users] => Array
  471. * (
  472. * [0] => moodle/user:viewdetails
  473. * [1] => moodle/user:viewhiddendetails
  474. * [2] => moodle/course:useremail
  475. * [3] => moodle/user:update
  476. * [4] => moodle/site:accessallgroups
  477. * )
  478. * )
  479. * @param int $serviceid service id
  480. * @return array
  481. */
  482. public function get_service_required_capabilities($serviceid) {
  483. $functions = $this->get_external_functions(array($serviceid));
  484. $requiredusercaps = array();
  485. foreach ($functions as $function) {
  486. $functioncaps = explode(',', $function->capabilities);
  487. if (!empty($functioncaps) and !empty($functioncaps[0])) {
  488. foreach ($functioncaps as $functioncap) {
  489. $requiredusercaps[$function->name][] = trim($functioncap);
  490. }
  491. }
  492. }
  493. return $requiredusercaps;
  494. }
  495. /**
  496. * Get user capabilities (with context)
  497. * Only useful for documentation purpose
  498. * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
  499. * required by users. In theory we should not need to display this kind of information
  500. * as the front end does not display it itself. In pratice,
  501. * admins would like the info, for more info you can follow: MDL-29962
  502. *
  503. * @param int $userid user id
  504. * @return array
  505. */
  506. public function get_user_capabilities($userid) {
  507. global $DB;
  508. //retrieve the user capabilities
  509. $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
  510. WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
  511. $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
  512. $usercaps = array();
  513. foreach ($dbusercaps as $usercap) {
  514. $usercaps[$usercap->capability] = true;
  515. }
  516. return $usercaps;
  517. }
  518. /**
  519. * Get missing user capabilities for a given service
  520. * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
  521. * required by users. In theory we should not need to display this kind of information
  522. * as the front end does not display it itself. In pratice,
  523. * admins would like the info, for more info you can follow: MDL-29962
  524. *
  525. * @param array $users users
  526. * @param int $serviceid service id
  527. * @return array of missing capabilities, keys being the user ids
  528. */
  529. public function get_missing_capabilities_by_users($users, $serviceid) {
  530. global $DB;
  531. $usersmissingcaps = array();
  532. //retrieve capabilities required by the service
  533. $servicecaps = $this->get_service_required_capabilities($serviceid);
  534. //retrieve users missing capabilities
  535. foreach ($users as $user) {
  536. //cast user array into object to be a bit more flexible
  537. if (is_array($user)) {
  538. $user = (object) $user;
  539. }
  540. $usercaps = $this->get_user_capabilities($user->id);
  541. //detect the missing capabilities
  542. foreach ($servicecaps as $functioname => $functioncaps) {
  543. foreach ($functioncaps as $functioncap) {
  544. if (!array_key_exists($functioncap, $usercaps)) {
  545. if (!isset($usersmissingcaps[$user->id])
  546. or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
  547. $usersmissingcaps[$user->id][] = $functioncap;
  548. }
  549. }
  550. }
  551. }
  552. }
  553. return $usersmissingcaps;
  554. }
  555. /**
  556. * Get an external service for a given service id
  557. *
  558. * @param int $serviceid service id
  559. * @param int $strictness IGNORE_MISSING, MUST_EXIST...
  560. * @return stdClass external service
  561. */
  562. public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
  563. global $DB;
  564. $service = $DB->get_record('external_services',
  565. array('id' => $serviceid), '*', $strictness);
  566. return $service;
  567. }
  568. /**
  569. * Get an external service for a given shortname
  570. *
  571. * @param string $shortname service shortname
  572. * @param int $strictness IGNORE_MISSING, MUST_EXIST...
  573. * @return stdClass external service
  574. */
  575. public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
  576. global $DB;
  577. $service = $DB->get_record('external_services',
  578. array('shortname' => $shortname), '*', $strictness);
  579. return $service;
  580. }
  581. /**
  582. * Get an external function for a given function id
  583. *
  584. * @param int $functionid function id
  585. * @param int $strictness IGNORE_MISSING, MUST_EXIST...
  586. * @return stdClass external function
  587. */
  588. public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
  589. global $DB;
  590. $function = $DB->get_record('external_functions',
  591. array('id' => $functionid), '*', $strictness);
  592. return $function;
  593. }
  594. /**
  595. * Add a function to a service
  596. *
  597. * @param string $functionname function name
  598. * @param int $serviceid service id
  599. */
  600. public function add_external_function_to_service($functionname, $serviceid) {
  601. global $DB;
  602. $addedfunction = new stdClass();
  603. $addedfunction->externalserviceid = $serviceid;
  604. $addedfunction->functionname = $functionname;
  605. $DB->insert_record('external_services_functions', $addedfunction);
  606. }
  607. /**
  608. * Add a service
  609. * It generates the timecreated field automatically.
  610. *
  611. * @param stdClass $service
  612. * @return serviceid integer
  613. */
  614. public function add_external_service($service) {
  615. global $DB;
  616. $service->timecreated = time();
  617. $serviceid = $DB->insert_record('external_services', $service);
  618. return $serviceid;
  619. }
  620. /**
  621. * Update a service
  622. * It modifies the timemodified automatically.
  623. *
  624. * @param stdClass $service
  625. */
  626. public function update_external_service($service) {
  627. global $DB;
  628. $service->timemodified = time();
  629. $DB->update_record('external_services', $service);
  630. }
  631. /**
  632. * Test whether an external function is already linked to a service
  633. *
  634. * @param string $functionname function name
  635. * @param int $serviceid service id
  636. * @return bool true if a matching function exists for the service, else false.
  637. * @throws dml_exception if error
  638. */
  639. public function service_function_exists($functionname, $serviceid) {
  640. global $DB;
  641. return $DB->record_exists('external_services_functions',
  642. array('externalserviceid' => $serviceid,
  643. 'functionname' => $functionname));
  644. }
  645. /**
  646. * Remove a function from a service
  647. *
  648. * @param string $functionname function name
  649. * @param int $serviceid service id
  650. */
  651. public function remove_external_function_from_service($functionname, $serviceid) {
  652. global $DB;
  653. $DB->delete_records('external_services_functions',
  654. array('externalserviceid' => $serviceid, 'functionname' => $functionname));
  655. }
  656. }
  657. /**
  658. * Exception indicating access control problem in web service call
  659. * This exception should return general errors about web service setup.
  660. * Errors related to the user like wrong username/password should not use it,
  661. * you should not use this exception if you want to let the client implement
  662. * some code logic against an access error.
  663. *
  664. * @package core_webservice
  665. * @copyright 2009 Petr Skodak
  666. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  667. */
  668. class webservice_access_exception extends moodle_exception {
  669. /**
  670. * Constructor
  671. *
  672. * @param string $debuginfo the debug info
  673. */
  674. function __construct($debuginfo) {
  675. parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
  676. }
  677. }
  678. /**
  679. * Check if a protocol is enabled
  680. *
  681. * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc'...)
  682. * @return bool true if the protocol is enabled
  683. */
  684. function webservice_protocol_is_enabled($protocol) {
  685. global $CFG;
  686. if (empty($CFG->enablewebservices)) {
  687. return false;
  688. }
  689. $active = explode(',', $CFG->webserviceprotocols);
  690. return(in_array($protocol, $active));
  691. }
  692. /**
  693. * Mandatory interface for all test client classes.
  694. *
  695. * @package core_webservice
  696. * @copyright 2009 Petr Skodak
  697. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  698. */
  699. interface webservice_test_client_interface {
  700. /**
  701. * Execute test client WS request
  702. *
  703. * @param string $serverurl server url (including the token param)
  704. * @param string $function web service function name
  705. * @param array $params parameters of the web service function
  706. * @return mixed
  707. */
  708. public function simpletest($serverurl, $function, $params);
  709. }
  710. /**
  711. * Mandatory interface for all web service protocol classes
  712. *
  713. * @package core_webservice
  714. * @copyright 2009 Petr Skodak
  715. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  716. */
  717. interface webservice_server_interface {
  718. /**
  719. * Process request from client.
  720. */
  721. public function run();
  722. }
  723. /**
  724. * Abstract web service base class.
  725. *
  726. * @package core_webservice
  727. * @copyright 2009 Petr Skodak
  728. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  729. */
  730. abstract class webservice_server implements webservice_server_interface {
  731. /** @var string Name of the web server plugin */
  732. protected $wsname = null;
  733. /** @var string Name of local user */
  734. protected $username = null;
  735. /** @var string Password of the local user */
  736. protected $password = null;
  737. /** @var int The local user */
  738. protected $userid = null;
  739. /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
  740. protected $authmethod;
  741. /** @var string Authentication token*/
  742. protected $token = null;
  743. /** @var stdClass Restricted context */
  744. protected $restricted_context;
  745. /** @var int Restrict call to one service id*/
  746. protected $restricted_serviceid = null;
  747. /**
  748. * Constructor
  749. *
  750. * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
  751. */
  752. public function __construct($authmethod) {
  753. $this->authmethod = $authmethod;
  754. }
  755. /**
  756. * Authenticate user using username+password or token.
  757. * This function sets up $USER global.
  758. * It is safe to use has_capability() after this.
  759. * This method also verifies user is allowed to use this
  760. * server.
  761. */
  762. protected function authenticate_user() {
  763. global $CFG, $DB;
  764. if (!NO_MOODLE_COOKIES) {
  765. throw new coding_exception('Cookies must be disabled in WS servers!');
  766. }
  767. $loginfaileddefaultparams = array(
  768. 'context' => context_system::instance(),
  769. 'other' => array(
  770. 'method' => $this->authmethod,
  771. 'reason' => null
  772. )
  773. );
  774. if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
  775. //we check that authentication plugin is enabled
  776. //it is only required by simple authentication
  777. if (!is_enabled_auth('webservice')) {
  778. throw new webservice_access_exception('The web service authentication plugin is disabled.');
  779. }
  780. if (!$auth = get_auth_plugin('webservice')) {
  781. throw new webservice_access_exception('The web service authentication plugin is missing.');
  782. }
  783. $this->restricted_context = context_system::instance();
  784. if (!$this->username) {
  785. throw new moodle_exception('missingusername', 'webservice');
  786. }
  787. if (!$this->password) {
  788. throw new moodle_exception('missingpassword', 'webservice');
  789. }
  790. if (!$auth->user_login_webservice($this->username, $this->password)) {
  791. // Log failed login attempts.
  792. $params = $loginfaileddefaultparams;
  793. $params['other']['reason'] = 'password';
  794. $params['other']['username'] = $this->username;
  795. $event = \core\event\webservice_login_failed::create($params);
  796. $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
  797. get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
  798. $event->trigger();
  799. throw new moodle_exception('wrongusernamepassword', 'webservice');
  800. }
  801. $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
  802. } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
  803. $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
  804. } else {
  805. $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
  806. }
  807. //Non admin can not authenticate if maintenance mode
  808. $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user);
  809. if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) {
  810. throw new moodle_exception('sitemaintenance', 'admin');
  811. }
  812. //only confirmed user should be able to call web service
  813. if (!empty($user->deleted)) {
  814. $params = $loginfaileddefaultparams;
  815. $params['other']['reason'] = 'user_deleted';
  816. $params['other']['username'] = $user->username;
  817. $event = \core\event\webservice_login_failed::create($params);
  818. $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
  819. $user->username) . " - ".getremoteaddr(), 0, $user->id));
  820. $event->trigger();
  821. throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username);
  822. }
  823. //only confirmed user should be able to call web service
  824. if (empty($user->confirmed)) {
  825. $params = $loginfaileddefaultparams;
  826. $params['other']['reason'] = 'user_unconfirmed';
  827. $params['other']['username'] = $user->username;
  828. $event = \core\event\webservice_login_failed::create($params);
  829. $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
  830. $user->username) . " - ".getremoteaddr(), 0, $user->id));
  831. $event->trigger();
  832. throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
  833. }
  834. //check the user is suspended
  835. if (!empty($user->suspended)) {
  836. $params = $loginfaileddefaultparams;
  837. $params['other']['reason'] = 'user_unconfirmed';
  838. $params['other']['username'] = $user->username;
  839. $event = \core\event\webservice_login_failed::create($params);
  840. $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
  841. $user->username) . " - ".getremoteaddr(), 0, $user->id));
  842. $event->trigger();
  843. throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
  844. }
  845. //retrieve the authentication plugin if no previously done
  846. if (empty($auth)) {
  847. $auth = get_auth_plugin($user->auth);
  848. }
  849. // check if credentials have expired
  850. if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
  851. $days2expire = $auth->password_expire($user->username);
  852. if (intval($days2expire) < 0 ) {
  853. $params = $loginfaileddefaultparams;
  854. $params['other']['reason'] = 'password_expired';
  855. $params['other']['username'] = $user->username;
  856. $event = \core\event\webservice_login_failed::create($params);
  857. $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
  858. $user->username) . " - ".getremoteaddr(), 0, $user->id));
  859. $event->trigger();
  860. throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username);
  861. }
  862. }
  863. //check if the auth method is nologin (in this case refuse connection)
  864. if ($user->auth=='nologin') {
  865. $params = $loginfaileddefaultparams;
  866. $params['other']['reason'] = 'login';
  867. $params['other']['username'] = $user->username;
  868. $event = \core\event\webservice_login_failed::create($params);
  869. $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
  870. $user->username) . " - ".getremoteaddr(), 0, $user->id));
  871. $event->trigger();
  872. throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
  873. }
  874. // now fake user login, the session is completely empty too
  875. enrol_check_plugins($user);
  876. \core\session\manager::set_user($user);
  877. $this->userid = $user->id;
  878. if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
  879. throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
  880. }
  881. external_api::set_context_restriction($this->restricted_context);
  882. }
  883. /**
  884. * User authentication by token
  885. *
  886. * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
  887. * @return stdClass the authenticated user
  888. * @throws webservice_access_exception
  889. */
  890. protected function authenticate_by_token($tokentype){
  891. global $DB;
  892. $loginfaileddefaultparams = array(
  893. 'context' => context_system::instance(),
  894. 'other' => array(
  895. 'method' => $this->authmethod,
  896. 'reason' => null
  897. )
  898. );
  899. if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
  900. // Log failed login attempts.
  901. $params = $loginfaileddefaultparams;
  902. $params['other']['reason'] = 'invalid_token';
  903. $event = \core\event\webservice_login_failed::create($params);
  904. $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
  905. get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0));
  906. $event->trigger();
  907. throw new moodle_exception('invalidtoken', 'webservice');
  908. }
  909. if ($token->validuntil and $token->validuntil < time()) {
  910. $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
  911. throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
  912. }
  913. if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
  914. if (!\core\session\manager::session_exists($token->sid)){
  915. $DB->delete_records('external_tokens', array('sid'=>$token->sid));
  916. throw new webservice_access_exception('Invalid session based token - session not found or expired');
  917. }
  918. }
  919. if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
  920. $params = $loginfaileddefaultparams;
  921. $params['other']['reason'] = 'ip_restricted';
  922. $params['other']['tokenid'] = $token->id;
  923. $event = \core\event\webservice_login_failed::create($params);
  924. $event->add_record_snapshot('external_tokens', $token);
  925. $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
  926. get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
  927. $event->trigger();
  928. throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
  929. . ' is not supported - check this allowed user');
  930. }
  931. $this->restricted_context = context::instance_by_id($token->contextid);
  932. $this->restricted_serviceid = $token->externalserviceid;
  933. $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
  934. // log token access
  935. $DB->set_field('external_tokens', 'lastaccess', time(), array('id'=>$token->id));
  936. return $user;
  937. }
  938. /**
  939. * Intercept some moodlewssettingXXX $_GET and $_POST parameter
  940. * that are related to the web service call and are not the function parameters
  941. */
  942. protected function set_web_service_call_settings() {
  943. global $CFG;
  944. // Default web service settings.
  945. // Must be the same XXX key name as the external_settings::set_XXX function.
  946. // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
  947. $externalsettings = array(
  948. 'raw' => false,
  949. 'fileurl' => true,
  950. 'filter' => false);
  951. // Load the external settings with the web service settings.
  952. $settings = external_settings::get_instance();
  953. foreach ($externalsettings as $name => $default) {
  954. $wsparamname = 'moodlewssetting' . $name;
  955. // Retrieve and remove the setting parameter from the request.
  956. $value = optional_param($wsparamname, $default, PARAM_BOOL);
  957. unset($_GET[$wsparamname]);
  958. unset($_POST[$wsparamname]);
  959. $functioname = 'set_' . $name;
  960. $settings->$functioname($value);
  961. }
  962. }
  963. }
  964. /**
  965. * Web Service server base class.
  966. *
  967. * This class handles both simple and token authentication.
  968. *
  969. * @package core_webservice
  970. * @copyright 2009 Petr Skodak
  971. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  972. */
  973. abstract class webservice_base_server extends webservice_server {
  974. /** @var array The function parameters - the real values submitted in the request */
  975. protected $parameters = null;
  976. /** @var string The name of the function that is executed */
  977. protected $functionname = null;
  978. /** @var stdClass Full function description */
  979. protected $function = null;
  980. /** @var mixed Function return value */
  981. protected $returns = null;
  982. /** @var array List of methods and their information provided by the web service. */
  983. protected $servicemethods;
  984. /** @var array List of struct classes generated for the web service methods. */
  985. protected $servicestructs;
  986. /**
  987. * This method parses the request input, it needs to get:
  988. * 1/ user authentication - username+password or token
  989. * 2/ function name
  990. * 3/ function parameters
  991. */
  992. abstract protected function parse_request();
  993. /**
  994. * Send the result of function call to the WS client.
  995. */
  996. abstract protected function send_response();
  997. /**
  998. * Send the error information to the WS client.
  999. *
  1000. * @param exception $ex
  1001. */
  1002. abstract protected function send_error($ex=null);
  1003. /**
  1004. * Process request from client.
  1005. *
  1006. * @uses die
  1007. */
  1008. public function run() {
  1009. // we will probably need a lot of memory in some functions
  1010. raise_memory_limit(MEMORY_EXTRA);
  1011. // set some longer timeout, this script is not sending any output,
  1012. // this means we need to manually extend the timeout operations
  1013. // that need longer time to finish
  1014. external_api::set_timeout();
  1015. // set up exception handler first, we want to sent them back in correct format that
  1016. // the other system understands
  1017. // we do not need to call the original default handler because this ws handler does everything
  1018. set_exception_handler(array($this, 'exception_handler'));
  1019. // init all properties from the request data
  1020. $this->parse_request();
  1021. // authenticate user, this has to be done after the request parsing
  1022. // this also sets up $USER and $SESSION
  1023. $this->authenticate_user();
  1024. // find all needed function info and make sure user may actually execute the function
  1025. $this->load_function_info();
  1026. // Log the web service request.
  1027. $params = array(
  1028. 'other' => array(
  1029. 'function' => $this->functionname
  1030. )
  1031. );
  1032. $event = \core\event\webservice_function_called::create($params);
  1033. $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid));
  1034. $event->trigger();
  1035. // finally, execute the function - any errors are catched by the default exception handler
  1036. $this->execute();
  1037. // send the results back in correct format
  1038. $this->send_response();
  1039. // session cleanup
  1040. $this->session_cleanup();
  1041. die;
  1042. }
  1043. /**
  1044. * Specialised exception handler, we can not use the standard one because
  1045. * it can not just print html to output.
  1046. *
  1047. * @param exception $ex
  1048. * $uses exit
  1049. */
  1050. public function exception_handler($ex) {
  1051. // detect active db transactions, rollback and log as error
  1052. abort_all_db_transactions();
  1053. // some hacks might need a cleanup hook
  1054. $this->session_cleanup($ex);
  1055. // now let the plugin send the exception to client
  1056. $this->send_error($ex);
  1057. // not much else we can do now, add some logging later
  1058. exit(1);
  1059. }
  1060. /**
  1061. * Future hook needed for emulated sessions.
  1062. *
  1063. * @param exception $exception null means normal termination, $exception received when WS call failed
  1064. */
  1065. protected function session_cleanup($exception=null) {
  1066. if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
  1067. // nothing needs to be done, there is no persistent session
  1068. } else {
  1069. // close emulated session if used
  1070. }
  1071. }
  1072. /**
  1073. * Fetches the function description from database,
  1074. * verifies user is allowed to use this function and
  1075. * loads all paremeters and return descriptions.
  1076. */
  1077. protected function load_function_info() {
  1078. global $DB, $USER, $CFG;
  1079. if (empty($this->functionname)) {
  1080. throw new invalid_parameter_exception('Missing function name');
  1081. }
  1082. // function must exist
  1083. $function = external_api::external_function_info($this->functionname);
  1084. if ($this->restricted_serviceid) {
  1085. $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
  1086. $wscond1 = 'AND s.id = :sid1';
  1087. $wscond2 = 'AND s.id = :sid2';
  1088. } else {
  1089. $params = array();
  1090. $wscond1 = '';
  1091. $wscond2 = '';
  1092. }
  1093. // now let's verify access control
  1094. // now make sure the function is listed in at least one service user is allowed to use
  1095. // allow access only if:
  1096. // 1/ entry in the external_services_users table if required
  1097. // 2/ validuntil not reached
  1098. // 3/ has capability if specified in service desc
  1099. // 4/ iprestriction
  1100. $sql = "SELECT s.*, NULL AS iprestriction
  1101. FROM {external_services} s
  1102. JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
  1103. WHERE s.enabled = 1 $wscond1
  1104. UNION
  1105. SELECT s.*, su.iprestriction
  1106. FROM {external_services} s
  1107. JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
  1108. JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
  1109. WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
  1110. $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
  1111. $rs = $DB->get_recordset_sql($sql, $params);
  1112. // now make sure user may access at least one service
  1113. $remoteaddr = getremoteaddr();
  1114. $allowed = false;
  1115. foreach ($rs as $service) {
  1116. if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
  1117. continue; // cap required, sorry
  1118. }
  1119. if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
  1120. continue; // wrong request source ip, sorry
  1121. }
  1122. $allowed = true;
  1123. break; // one service is enough, no need to continue
  1124. }
  1125. $rs->close();
  1126. if (!$allowed) {
  1127. throw new webservice_access_exception(
  1128. 'Access to the function '.$this->functionname.'() is not allowed.
  1129. There could be multiple reasons for this:
  1130. 1. The service linked to the user token does not contain the function.
  1131. 2. The service is user-restricted and the user is not listed.
  1132. 3. The service is IP-restricted and the user IP is not listed.
  1133. 4. The service is time-restricted and the time has expired.
  1134. 5. The token is time-restricted and the time has expired.
  1135. 6. The service requires a specific capability which the user does not have.
  1136. 7. The function is called with username/password (no user token is sent)
  1137. and none of the services has the function to allow the user.
  1138. These settings can be found in Administration > Site administration
  1139. > Plugins > Web services > External services and Manage tokens.');
  1140. }
  1141. // we have all we need now
  1142. $this->function = $function;
  1143. }
  1144. /**
  1145. * Execute previously loaded function using parameters parsed from the request data.
  1146. */
  1147. protected function execute() {
  1148. // validate params, this also sorts the params properly, we need the correct order in the next part
  1149. $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
  1150. // execute - yay!
  1151. $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), array_values($params));
  1152. }
  1153. /**
  1154. * Load the virtual class needed for the web service.
  1155. *
  1156. * Initialises the virtual class that contains the web service functions that the user is allowed to use.
  1157. * The web service function will be available if the user:
  1158. * - is validly registered in the external_services_users table.
  1159. * - has the required capability.
  1160. * - meets the IP restriction requirement.
  1161. * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
  1162. */
  1163. protected function init_service_class() {
  1164. global $USER, $DB;
  1165. // Initialise service methods and struct classes.
  1166. $this->servicemethods = array();
  1167. $this->servicestructs = array();
  1168. $params = array();
  1169. $wscond1 = '';
  1170. $wscond2 = '';
  1171. if ($this->restricted_serviceid) {
  1172. $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
  1173. $wscond1 = 'AND s.id = :sid1';
  1174. $wscond2 = 'AND s.id = :sid2';
  1175. }
  1176. $sql = "SELECT s.*, NULL AS iprestriction
  1177. FROM {external_services} s
  1178. JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
  1179. WHERE s.enabled = 1 $wscond1
  1180. UNION
  1181. SELECT s.*, su.iprestriction
  1182. FROM {external_services} s
  1183. JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
  1184. JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
  1185. WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
  1186. $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
  1187. $serviceids = array();
  1188. $remoteaddr = getremoteaddr();
  1189. // Query list of external services for the user.
  1190. $rs = $DB->get_recordset_sql($sql, $params);
  1191. // Check which service ID to include.
  1192. foreach ($rs as $service) {
  1193. if (isset($serviceids[$service->id])) {
  1194. continue; // Service already added.
  1195. }
  1196. if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
  1197. continue; // Cap required, sorry.
  1198. }
  1199. if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
  1200. continue; // Wrong request source ip, sorry.
  1201. }
  1202. $serviceids[$service->id] = $service->id;
  1203. }
  1204. $rs->close();
  1205. // Generate the virtual class name.
  1206. $classname = 'webservices_virtual_class_000000';
  1207. while (class_exists($classname)) {
  1208. $classname++;
  1209. }
  1210. $this->serviceclass = $classname;
  1211. // Get the list of all available external functions.
  1212. $wsmanager = new webservice();
  1213. $functions = $wsmanager->get_external_functions($serviceids);
  1214. // Generate code for the virtual methods for this web service.
  1215. $methods = '';
  1216. foreach ($functions as $function) {
  1217. $methods .= $this->get_virtual_method_code($function);
  1218. }
  1219. $code = <<<EOD
  1220. /**
  1221. * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}.
  1222. */
  1223. class $classname {
  1224. $methods
  1225. }
  1226. EOD;
  1227. // Load the virtual class definition into memory.
  1228. eval($code);
  1229. }
  1230. /**
  1231. * Generates a struct class.
  1232. *
  1233. * @param external_single_structure $structdesc The basis of the struct class to be generated.
  1234. * @return string The class name of the generated struct class.
  1235. */
  1236. protected function generate_simple_struct_class(external_single_structure $structdesc) {
  1237. global $USER;
  1238. $propeties = array();
  1239. $fields = array();
  1240. foreach ($structdesc->keys as $name => $fieldsdesc) {
  1241. $type = $this->get_phpdoc_type($fieldsdesc);
  1242. $propertytype = array('type' => $type);
  1243. if (empty($fieldsdesc->allownull) || $fieldsdesc->allownull == NULL_ALLOWED) {
  1244. $propertytype['nillable'] = true;
  1245. }
  1246. $propeties[$name] = $propertytype;
  1247. $fields[] = ' /** @var ' . $type . ' $' . $name . '*/';
  1248. $fields[] = ' public $' . $name .';';
  1249. }
  1250. $fieldsstr = implode("\n", $fields);
  1251. // We do this after the call to get_phpdoc_type() to avoid duplicate class creation.
  1252. $classname = 'webservices_struct_class_000000';
  1253. while (class_exists($classname)) {
  1254. $classname++;
  1255. }
  1256. $code = <<<EOD
  1257. /**
  1258. * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}.
  1259. */
  1260. class $classname {
  1261. $fieldsstr
  1262. }
  1263. EOD;
  1264. // Load into memory.
  1265. eval($code);
  1266. // Prepare struct info.
  1267. $structinfo = new stdClass();
  1268. $structinfo->classname = $classname;
  1269. $structinfo->properties = $propeties;
  1270. // Add the struct info the the list of service struct classes.
  1271. $this->servicestructs[] = $structinfo;
  1272. return $classname;
  1273. }
  1274. /**
  1275. * Returns a virtual method code for a web service function.
  1276. *
  1277. * @param stdClass $function a record from external_function
  1278. * @return string The PHP code of the virtual method.
  1279. * @throws coding_exception
  1280. * @throws moodle_exception
  1281. */
  1282. protected function get_virtual_method_code($function) {
  1283. $function = external_api::external_function_info($function);
  1284. // Parameters and their defaults for the method signature.
  1285. $paramanddefaults = array();
  1286. // Parameters for external lib call.
  1287. $params = array();
  1288. $paramdesc = array();
  1289. // The method's input parameters and their respective types.
  1290. $inputparams = array();
  1291. // The method's output parameters and their respective types.
  1292. $outputparams = array();
  1293. foreach ($function->parameters_desc->keys as $name => $keydesc) {
  1294. $param = '$' . $name;
  1295. $paramanddefault = $param;
  1296. if ($keydesc->required == VALUE_OPTIONAL) {
  1297. // It does not make sense to declare a parameter VALUE_OPTIONAL. VALUE_OPTIONAL is used only for array/object key.
  1298. throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
  1299. } else if ($keydesc->required == VALUE_DEFAULT) {
  1300. // Need to generate the default, if there is any.
  1301. if ($keydesc instanceof external_value) {
  1302. if ($keydesc->default === null) {
  1303. $paramanddefault .= ' = null';
  1304. } else {
  1305. switch ($keydesc->type) {
  1306. case PARAM_BOOL:
  1307. $default = (int)$keydesc->default;
  1308. break;
  1309. case PARAM_INT:
  1310. $default = $keydesc->default;
  1311. break;
  1312. case PARAM_FLOAT;
  1313. $default = $keydesc->default;
  1314. break;
  1315. default:
  1316. $default = "'$keydesc->default'";
  1317. }
  1318. $paramanddefault .= " = $default";
  1319. }
  1320. } else {
  1321. // Accept empty array as default.
  1322. if (isset($keydesc->default) && is_array($keydesc->default) && empty($keydesc->default)) {
  1323. $paramanddefault .= ' = array()';
  1324. } else {
  1325. // For the moment we do not support default for other structure types.
  1326. throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
  1327. }
  1328. }
  1329. }
  1330. $params[] = $param;
  1331. $paramanddefaults[] = $paramanddefault;
  1332. $type = $this->get_phpdoc_type($keydesc);
  1333. $inputparams[$name]['type'] = $type;
  1334. $paramdesc[] = '* @param ' . $type . ' $' . $name . ' ' . $keydesc->desc;
  1335. }
  1336. $paramanddefaults = implode(', ', $paramanddefaults);
  1337. $paramdescstr = implode("\n ", $paramdesc);
  1338. $serviceclassmethodbody = $this->service_class_method_body($function, $params);
  1339. if (empty($function->returns_desc)) {
  1340. $return = '* @return void';
  1341. } else {
  1342. $type = $this->get_phpdoc_type($function->returns_desc);
  1343. $outputparams['return']['type'] = $type;
  1344. $return = '* @return ' . $type . ' ' . $function->returns_desc->desc;
  1345. }
  1346. // Now create the virtual method that calls the ext implementation.
  1347. $code = <<<EOD
  1348. /**
  1349. * $function->description.
  1350. *
  1351. $paramdescstr
  1352. $return
  1353. */
  1354. public function $function->name($paramanddefaults) {
  1355. $serviceclassmethodbody
  1356. }
  1357. EOD;
  1358. // Prepare the method information.
  1359. $methodinfo = new stdClass();
  1360. $methodinfo->name = $function->name;
  1361. $methodinfo->inputparams = $inputparams;
  1362. $methodinfo->outputparams = $outputparams;
  1363. $methodinfo->description = $function->description;
  1364. // Add the method information into the list of service methods.
  1365. $this->servicemethods[] = $methodinfo;
  1366. return $code;
  1367. }
  1368. /**
  1369. * Get the phpdoc type for an external_description object.
  1370. * external_value => int, double or string
  1371. * external_single_structure => object|struct, on-fly generated stdClass name.
  1372. * external_multiple_structure => array
  1373. *
  1374. * @param mixed $keydesc The type description.
  1375. * @return string The PHP doc type of the external_description object.
  1376. */
  1377. protected function get_phpdoc_type($keydesc) {
  1378. $type = null;
  1379. if ($keydesc instanceof external_value) {
  1380. switch ($keydesc->type) {
  1381. case PARAM_BOOL: // 0 or 1 only for now.
  1382. case PARAM_INT:
  1383. $type = 'int';
  1384. break;
  1385. case PARAM_FLOAT;
  1386. $type = 'double';
  1387. break;
  1388. default:
  1389. $type = 'string';
  1390. }
  1391. } else if ($keydesc instanceof external_single_structure) {
  1392. $type = $this->generate_simple_struct_class($keydesc);
  1393. } else if ($keydesc instanceof external_multiple_structure) {
  1394. $type = 'array';
  1395. }
  1396. return $type;
  1397. }
  1398. /**
  1399. * Generates the method body of the virtual external function.
  1400. *
  1401. * @param stdClass $function a record from external_function.
  1402. * @param array $params web service function parameters.
  1403. * @return string body of the method for $function ie. everything within the {} of the method declaration.
  1404. */
  1405. protected function service_class_method_body($function, $params) {
  1406. // Cast the param from object to array (validate_parameters except array only).
  1407. $castingcode = '';
  1408. $paramsstr = '';
  1409. if (!empty($params)) {
  1410. foreach ($params as $paramtocast) {
  1411. // Clean the parameter from any white space.
  1412. $paramtocast = trim($paramtocast);
  1413. $castingcode .= " $paramtocast = json_decode(json_encode($paramtocast), true);\n";
  1414. }
  1415. $paramsstr = implode(', ', $params);
  1416. }
  1417. $descriptionmethod = $function->methodname . '_returns()';
  1418. $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod;
  1419. $methodbody = <<<EOD
  1420. $castingcode
  1421. if ($callforreturnvaluedesc == null) {
  1422. $function->classname::$function->methodname($paramsstr);
  1423. return null;
  1424. }
  1425. return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr));
  1426. EOD;
  1427. return $methodbody;
  1428. }
  1429. }