Merge branch 'MDL-56938-master-fix1' of http://github.com/damyon/moodle
[moodle.git] / notes / externallib.php
blob6c07faffeb0037c801c43d7eecfe98c5cd48827c
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.
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/>.
18 /**
19 * External notes API
21 * @package core_notes
22 * @category external
23 * @copyright 2011 Jerome Mouneyrac
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once("$CFG->libdir/externallib.php");
28 require_once($CFG->dirroot . "/notes/lib.php");
30 /**
31 * Notes external functions
33 * @package core_notes
34 * @category external
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 * @since Moodle 2.2
39 class core_notes_external extends external_api {
41 /**
42 * Returns description of method parameters
44 * @return external_function_parameters
45 * @since Moodle 2.2
47 public static function create_notes_parameters() {
48 return new external_function_parameters(
49 array(
50 'notes' => new external_multiple_structure(
51 new external_single_structure(
52 array(
53 'userid' => new external_value(PARAM_INT, 'id of the user the note is about'),
54 'publishstate' => new external_value(PARAM_ALPHA, '\'personal\', \'course\' or \'site\''),
55 'courseid' => new external_value(PARAM_INT, 'course id of the note (in Moodle a note can only be created into a course, even for site and personal notes)'),
56 'text' => new external_value(PARAM_RAW, 'the text of the message - text or HTML'),
57 'format' => new external_format_value('text', VALUE_DEFAULT),
58 'clientnoteid' => new external_value(PARAM_ALPHANUMEXT, 'your own client id for the note. If this id is provided, the fail message id will be returned to you', VALUE_OPTIONAL),
66 /**
67 * Create notes about some users
68 * Note: code should be matching the /notes/edit.php checks
69 * and the /user/addnote.php checks. (they are similar cheks)
71 * @param array $notes An array of notes to create.
72 * @return array (success infos and fail infos)
73 * @since Moodle 2.2
75 public static function create_notes($notes = array()) {
76 global $CFG, $DB;
78 $params = self::validate_parameters(self::create_notes_parameters(), array('notes' => $notes));
80 // Check if note system is enabled.
81 if (!$CFG->enablenotes) {
82 throw new moodle_exception('notesdisabled', 'notes');
85 // Retrieve all courses.
86 $courseids = array();
87 foreach ($params['notes'] as $note) {
88 $courseids[] = $note['courseid'];
90 $courses = $DB->get_records_list("course", "id", $courseids);
92 // Retrieve all users of the notes.
93 $userids = array();
94 foreach ($params['notes'] as $note) {
95 $userids[] = $note['userid'];
97 list($sqluserids, $sqlparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid_');
98 $users = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);
100 $resultnotes = array();
101 foreach ($params['notes'] as $note) {
103 $success = true;
104 $resultnote = array(); // The infos about the success of the operation.
106 // Check the course exists.
107 if (empty($courses[$note['courseid']])) {
108 $success = false;
109 $errormessage = get_string('invalidcourseid', 'error');
110 } else {
111 // Ensure the current user is allowed to run this function.
112 $context = context_course::instance($note['courseid']);
113 self::validate_context($context);
114 require_capability('moodle/notes:manage', $context);
117 // Check the user exists.
118 if (empty($users[$note['userid']])) {
119 $success = false;
120 $errormessage = get_string('invaliduserid', 'notes', $note['userid']);
123 // Build the resultnote.
124 if (isset($note['clientnoteid'])) {
125 $resultnote['clientnoteid'] = $note['clientnoteid'];
128 if ($success) {
129 // Now we can create the note.
130 $dbnote = new stdClass;
131 $dbnote->courseid = $note['courseid'];
132 $dbnote->userid = $note['userid'];
133 // Need to support 'html' and 'text' format values for backward compatibility.
134 switch (strtolower($note['format'])) {
135 case 'html':
136 $textformat = FORMAT_HTML;
137 break;
138 case 'text':
139 $textformat = FORMAT_PLAIN;
140 default:
141 $textformat = external_validate_format($note['format']);
142 break;
144 $dbnote->content = $note['text'];
145 $dbnote->format = $textformat;
147 // Get the state ('personal', 'course', 'site').
148 switch ($note['publishstate']) {
149 case 'personal':
150 $dbnote->publishstate = NOTES_STATE_DRAFT;
151 break;
152 case 'course':
153 $dbnote->publishstate = NOTES_STATE_PUBLIC;
154 break;
155 case 'site':
156 $dbnote->publishstate = NOTES_STATE_SITE;
157 $dbnote->courseid = SITEID;
158 break;
159 default:
160 break;
163 // TODO MDL-31119 performance improvement - if possible create a bulk functions for saving multiple notes at once
164 if (note_save($dbnote)) { // Note_save attribut an id in case of success.
165 $success = $dbnote->id;
168 $resultnote['noteid'] = $success;
169 } else {
170 // WARNINGS: for backward compatibility we return this errormessage.
171 // We should have thrown exceptions as these errors prevent results to be returned.
172 // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
173 $resultnote['noteid'] = -1;
174 $resultnote['errormessage'] = $errormessage;
177 $resultnotes[] = $resultnote;
180 return $resultnotes;
184 * Returns description of method result value
186 * @return external_description
187 * @since Moodle 2.2
189 public static function create_notes_returns() {
190 return new external_multiple_structure(
191 new external_single_structure(
192 array(
193 'clientnoteid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the note', VALUE_OPTIONAL),
194 'noteid' => new external_value(PARAM_INT, 'ID of the created note when successful, -1 when failed'),
195 'errormessage' => new external_value(PARAM_TEXT, 'error message - if failed', VALUE_OPTIONAL)
202 * Returns description of delete_notes parameters
204 * @return external_function_parameters
205 * @since Moodle 2.5
207 public static function delete_notes_parameters() {
208 return new external_function_parameters(
209 array(
210 "notes"=> new external_multiple_structure(
211 new external_value(PARAM_INT, 'ID of the note to be deleted'), 'Array of Note Ids to be deleted.'
218 * Delete notes about users.
219 * Note: code should be matching the /notes/delete.php checks.
221 * @param array $notes An array of ids for the notes to delete.
222 * @return null
223 * @since Moodle 2.5
225 public static function delete_notes($notes = array()) {
226 global $CFG;
228 $params = self::validate_parameters(self::delete_notes_parameters(), array('notes' => $notes));
230 // Check if note system is enabled.
231 if (!$CFG->enablenotes) {
232 throw new moodle_exception('notesdisabled', 'notes');
234 $warnings = array();
235 foreach ($params['notes'] as $noteid) {
236 $note = note_load($noteid);
237 if (isset($note->id)) {
238 // Ensure the current user is allowed to run this function.
239 $context = context_course::instance($note->courseid);
240 self::validate_context($context);
241 require_capability('moodle/notes:manage', $context);
242 note_delete($note);
243 } else {
244 $warnings[] = array('item'=>'note', 'itemid'=>$noteid, 'warningcode'=>'badid', 'message'=>'Note does not exist');
247 return $warnings;
251 * Returns description of delete_notes result value.
253 * @return external_description
254 * @since Moodle 2.5
256 public static function delete_notes_returns() {
257 return new external_warnings('item is always \'note\'',
258 'When errorcode is savedfailed the note could not be modified.' .
259 'When errorcode is badparam, an incorrect parameter was provided.' .
260 'When errorcode is badid, the note does not exist',
261 'errorcode can be badparam (incorrect parameter), savedfailed (could not be modified), or badid (note does not exist)');
266 * Returns description of get_notes parameters.
268 * @return external_function_parameters
269 * @since Moodle 2.5
271 public static function get_notes_parameters() {
272 return new external_function_parameters(
273 array(
274 "notes"=> new external_multiple_structure(
275 new external_value(PARAM_INT, 'ID of the note to be retrieved'), 'Array of Note Ids to be retrieved.'
282 * Get notes about users.
284 * @param array $notes An array of ids for the notes to retrieve.
285 * @return null
286 * @since Moodle 2.5
288 public static function get_notes($notes) {
289 global $CFG;
291 $params = self::validate_parameters(self::get_notes_parameters(), array('notes' => $notes));
292 // Check if note system is enabled.
293 if (!$CFG->enablenotes) {
294 throw new moodle_exception('notesdisabled', 'notes');
296 $resultnotes = array();
297 foreach ($params['notes'] as $noteid) {
298 $resultnote = array();
300 $note = note_load($noteid);
301 if (isset($note->id)) {
302 // Ensure the current user is allowed to run this function.
303 $context = context_course::instance($note->courseid);
304 self::validate_context($context);
305 require_capability('moodle/notes:view', $context);
306 list($gotnote['text'], $gotnote['format']) = external_format_text($note->content,
307 $note->format,
308 $context->id,
309 'notes',
311 '');
312 $gotnote['noteid'] = $note->id;
313 $gotnote['userid'] = $note->userid;
314 $gotnote['publishstate'] = $note->publishstate;
315 $gotnote['courseid'] = $note->courseid;
316 $resultnotes["notes"][] = $gotnote;
317 } else {
318 $resultnotes["warnings"][] = array('item' => 'note',
319 'itemid' => $noteid,
320 'warningcode' => 'badid',
321 'message' => 'Note does not exist');
324 return $resultnotes;
328 * Returns description of get_notes result value.
330 * @return external_description
331 * @since Moodle 2.5
333 public static function get_notes_returns() {
334 return new external_single_structure(
335 array(
336 'notes' => new external_multiple_structure(
337 new external_single_structure(
338 array(
339 'noteid' => new external_value(PARAM_INT, 'id of the note', VALUE_OPTIONAL),
340 'userid' => new external_value(PARAM_INT, 'id of the user the note is about', VALUE_OPTIONAL),
341 'publishstate' => new external_value(PARAM_ALPHA, '\'personal\', \'course\' or \'site\'', VALUE_OPTIONAL),
342 'courseid' => new external_value(PARAM_INT, 'course id of the note', VALUE_OPTIONAL),
343 'text' => new external_value(PARAM_RAW, 'the text of the message - text or HTML', VALUE_OPTIONAL),
344 'format' => new external_format_value('text', VALUE_OPTIONAL),
345 ), 'note'
348 'warnings' => new external_warnings('item is always \'note\'',
349 'When errorcode is savedfailed the note could not be modified.' .
350 'When errorcode is badparam, an incorrect parameter was provided.' .
351 'When errorcode is badid, the note does not exist',
352 'errorcode can be badparam (incorrect parameter), savedfailed (could not be modified), or badid (note does not exist)')
358 * Returns description of update_notes parameters.
360 * @return external_function_parameters
361 * @since Moodle 2.5
363 public static function update_notes_parameters() {
364 return new external_function_parameters(
365 array(
366 'notes' => new external_multiple_structure(
367 new external_single_structure(
368 array(
369 'id' => new external_value(PARAM_INT, 'id of the note'),
370 'publishstate' => new external_value(PARAM_ALPHA, '\'personal\', \'course\' or \'site\''),
371 'text' => new external_value(PARAM_RAW, 'the text of the message - text or HTML'),
372 'format' => new external_format_value('text', VALUE_DEFAULT),
374 ), "Array of Notes", VALUE_DEFAULT, array()
381 * Update notes about users.
383 * @param array $notes An array of ids for the notes to update.
384 * @return array fail infos.
385 * @since Moodle 2.2
387 public static function update_notes($notes = array()) {
388 global $CFG, $DB;
390 $params = self::validate_parameters(self::update_notes_parameters(), array('notes' => $notes));
392 // Check if note system is enabled.
393 if (!$CFG->enablenotes) {
394 throw new moodle_exception('notesdisabled', 'notes');
397 $warnings = array();
398 foreach ($params['notes'] as $note) {
399 $notedetails = note_load($note['id']);
400 if (isset($notedetails->id)) {
401 // Ensure the current user is allowed to run this function.
402 $context = context_course::instance($notedetails->courseid);
403 self::validate_context($context);
404 require_capability('moodle/notes:manage', $context);
406 $dbnote = new stdClass;
407 $dbnote->id = $note['id'];
408 $dbnote->content = $note['text'];
409 $dbnote->format = external_validate_format($note['format']);
410 // Get the state ('personal', 'course', 'site').
411 switch ($note['publishstate']) {
412 case 'personal':
413 $dbnote->publishstate = NOTES_STATE_DRAFT;
414 break;
415 case 'course':
416 $dbnote->publishstate = NOTES_STATE_PUBLIC;
417 break;
418 case 'site':
419 $dbnote->publishstate = NOTES_STATE_SITE;
420 $dbnote->courseid = SITEID;
421 break;
422 default:
423 $warnings[] = array('item' => 'note',
424 'itemid' => $note["id"],
425 'warningcode' => 'badparam',
426 'message' => 'Provided publishstate incorrect');
427 break;
429 if (!note_save($dbnote)) {
430 $warnings[] = array('item' => 'note',
431 'itemid' => $note["id"],
432 'warningcode' => 'savedfailed',
433 'message' => 'Note could not be modified');
435 } else {
436 $warnings[] = array('item' => 'note',
437 'itemid' => $note["id"],
438 'warningcode' => 'badid',
439 'message' => 'Note does not exist');
442 return $warnings;
446 * Returns description of update_notes result value.
448 * @return external_description
449 * @since Moodle 2.5
451 public static function update_notes_returns() {
452 return new external_warnings('item is always \'note\'',
453 'When errorcode is savedfailed the note could not be modified.' .
454 'When errorcode is badparam, an incorrect parameter was provided.' .
455 'When errorcode is badid, the note does not exist',
456 'errorcode can be badparam (incorrect parameter), savedfailed (could not be modified), or badid (note does not exist)');
460 * Returns description of method parameters
462 * @return external_function_parameters
463 * @since Moodle 2.9
465 public static function get_course_notes_parameters() {
466 return new external_function_parameters(
467 array(
468 'courseid' => new external_value(PARAM_INT, 'course id, 0 for SITE'),
469 'userid' => new external_value(PARAM_INT, 'user id', VALUE_DEFAULT, 0),
475 * Create a notes list
477 * @param int $courseid ID of the Course
478 * @param stdClass $context context object
479 * @param int $userid ID of the User
480 * @param int $state
481 * @param int $author
482 * @return array of notes
483 * @since Moodle 2.9
485 protected static function create_note_list($courseid, $context, $userid, $state, $author = 0) {
486 $results = array();
487 $notes = note_list($courseid, $userid, $state, $author);
488 foreach ($notes as $key => $note) {
489 $note = (array)$note;
490 list($note['content'], $note['format']) = external_format_text($note['content'],
491 $note['format'],
492 $context->id,
496 $results[$key] = $note;
498 return $results;
502 * Get a list of course notes
504 * @param int $courseid ID of the Course
505 * @param int $userid ID of the User
506 * @return array of site, course and personal notes and warnings
507 * @since Moodle 2.9
508 * @throws moodle_exception
510 public static function get_course_notes($courseid, $userid = 0) {
511 global $CFG, $USER;
513 if (empty($CFG->enablenotes)) {
514 throw new moodle_exception('notesdisabled', 'notes');
517 $warnings = array();
518 $arrayparams = array(
519 'courseid' => $courseid,
520 'userid' => $userid,
522 $params = self::validate_parameters(self::get_course_notes_parameters(), $arrayparams);
524 if (empty($params['courseid'])) {
525 $params['courseid'] = SITEID;
527 $user = null;
528 if (!empty($params['userid'])) {
529 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
530 core_user::require_active_user($user);
533 $course = get_course($params['courseid']);
535 if ($course->id == SITEID) {
536 $context = context_system::instance();
537 } else {
538 $context = context_course::instance($course->id);
540 self::validate_context($context);
542 $sitenotes = array();
543 $coursenotes = array();
544 $personalnotes = array();
546 if ($course->id != SITEID) {
548 require_capability('moodle/notes:view', $context);
549 $sitenotes = self::create_note_list(0, context_system::instance(), $params['userid'], NOTES_STATE_SITE);
550 $coursenotes = self::create_note_list($course->id, $context, $params['userid'], NOTES_STATE_PUBLIC);
551 $personalnotes = self::create_note_list($course->id, $context, $params['userid'], NOTES_STATE_DRAFT,
552 $USER->id);
553 } else {
554 if (has_capability('moodle/notes:view', $context)) {
555 $sitenotes = self::create_note_list(0, $context, $params['userid'], NOTES_STATE_SITE);
557 // It returns notes only for a specific user!
558 if (!empty($user)) {
559 $usercourses = enrol_get_users_courses($user->id, true);
560 foreach ($usercourses as $c) {
561 // All notes at course level, only if we have capability on every course.
562 if (has_capability('moodle/notes:view', context_course::instance($c->id))) {
563 $coursenotes += self::create_note_list($c->id, $context, $params['userid'], NOTES_STATE_PUBLIC);
569 $results = array(
570 'sitenotes' => $sitenotes,
571 'coursenotes' => $coursenotes,
572 'personalnotes' => $personalnotes,
573 'warnings' => $warnings
575 return $results;
580 * Returns array of note structure
582 * @return external_description
583 * @since Moodle 2.9
585 protected static function get_note_structure() {
586 return array(
587 'id' => new external_value(PARAM_INT, 'id of this note'),
588 'courseid' => new external_value(PARAM_INT, 'id of the course'),
589 'userid' => new external_value(PARAM_INT, 'user id'),
590 'content' => new external_value(PARAM_RAW, 'the content text formated'),
591 'format' => new external_format_value('content'),
592 'created' => new external_value(PARAM_INT, 'time created (timestamp)'),
593 'lastmodified' => new external_value(PARAM_INT, 'time of last modification (timestamp)'),
594 'usermodified' => new external_value(PARAM_INT, 'user id of the creator of this note'),
595 'publishstate' => new external_value(PARAM_ALPHA, "state of the note (i.e. draft, public, site) ")
600 * Returns description of method result value
602 * @return external_description
603 * @since Moodle 2.9
605 public static function get_course_notes_returns() {
606 return new external_single_structure(
607 array(
608 'sitenotes' => new external_multiple_structure(
609 new external_single_structure(
610 self::get_note_structure() , ''
611 ), 'site notes', VALUE_OPTIONAL
613 'coursenotes' => new external_multiple_structure(
614 new external_single_structure(
615 self::get_note_structure() , ''
616 ), 'couse notes', VALUE_OPTIONAL
618 'personalnotes' => new external_multiple_structure(
619 new external_single_structure(
620 self::get_note_structure() , ''
621 ), 'personal notes', VALUE_OPTIONAL
623 'warnings' => new external_warnings()
624 ), 'notes'
629 * Returns description of method parameters
631 * @return external_function_parameters
632 * @since Moodle 2.9
634 public static function view_notes_parameters() {
635 return new external_function_parameters(
636 array(
637 'courseid' => new external_value(PARAM_INT, 'course id, 0 for notes at system level'),
638 'userid' => new external_value(PARAM_INT, 'user id, 0 means view all the user notes', VALUE_DEFAULT, 0)
644 * Simulates the web interface view of notes/index.php: trigger events
646 * @param int $courseid id of the course
647 * @param int $userid id of the user
648 * @return array of warnings and status result
649 * @since Moodle 2.9
650 * @throws moodle_exception
652 public static function view_notes($courseid, $userid = 0) {
653 global $CFG;
654 require_once($CFG->dirroot . "/notes/lib.php");
656 if (empty($CFG->enablenotes)) {
657 throw new moodle_exception('notesdisabled', 'notes');
660 $warnings = array();
661 $arrayparams = array(
662 'courseid' => $courseid,
663 'userid' => $userid
665 $params = self::validate_parameters(self::view_notes_parameters(), $arrayparams);
667 if (empty($params['courseid'])) {
668 $params['courseid'] = SITEID;
671 $course = get_course($params['courseid']);
673 if ($course->id == SITEID) {
674 $context = context_system::instance();
675 } else {
676 $context = context_course::instance($course->id);
679 // First of all, validate the context before do further permission checks.
680 self::validate_context($context);
681 require_capability('moodle/notes:view', $context);
683 if (!empty($params['userid'])) {
684 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
685 core_user::require_active_user($user);
687 if ($course->id != SITEID and !can_access_course($course, $user, '', true)) {
688 throw new moodle_exception('notenrolledprofile');
692 note_view($context, $params['userid']);
694 $result = array();
695 $result['status'] = true;
696 $result['warnings'] = $warnings;
697 return $result;
702 * Returns description of method result value
704 * @return external_description
705 * @since Moodle 2.9
707 public static function view_notes_returns() {
708 return new external_single_structure(
709 array(
710 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
711 'warnings' => new external_warnings()