MDL-57407 mod_data: Return ratings in mod_data_get_entry
[moodle.git] / mod / data / tests / externallib_test.php
CommitLineData
067b3fda
JL
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/**
18 * Database module external functions tests
19 *
20 * @package mod_data
21 * @category external
22 * @copyright 2015 Juan Leyva <juan@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @since Moodle 2.9
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
30
31require_once($CFG->dirroot . '/webservice/tests/helpers.php');
32
33/**
34 * Database module external functions tests
35 *
36 * @package mod_data
37 * @category external
38 * @copyright 2015 Juan Leyva <juan@moodle.com>
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 * @since Moodle 2.9
41 */
42class mod_data_external_testcase extends externallib_advanced_testcase {
43
cefd780f
JP
44 /** @var stdClass Test module context. */
45 protected $context;
46
47 /** @var stdClass Test course.*/
48 protected $course;
49
50 /** @var stdClass Test course module. */
51 protected $cm;
52
53 /** @var stdClass Test database activity. */
54 protected $database;
55
56 /** @var stdClass Test group 1. */
57 protected $group1;
58
59 /** @var stdClass Test group 2. */
60 protected $group2;
61
62 /** @var stdClass Test student 1. */
63 protected $student1;
64
65 /** @var stdClass Test student 2. */
66 protected $student2;
67
68 /** @var stdClass Test student 3. */
69 protected $student3;
70
71 /** @var stdClass Test student 4. */
72 protected $student4;
73
74 /** @var stdClass Student role. */
75 protected $studentrole;
76
77 /** @var stdClass Test teacher. */
78 protected $teacher;
79
80 /** @var stdClass Teacher role. */
81 protected $teacherrole;
82
9fac7c86
JL
83 /**
84 * Set up for every test
85 */
86 public function setUp() {
87 global $DB;
88 $this->resetAfterTest();
89 $this->setAdminUser();
90
91 // Setup test data.
ef6aea9d
JL
92 $course = new stdClass();
93 $course->groupmode = SEPARATEGROUPS;
94 $course->groupmodeforce = true;
95 $this->course = $this->getDataGenerator()->create_course($course);
cefd780f
JP
96 $this->database = $this->getDataGenerator()->create_module('data', array('course' => $this->course->id));
97 $this->context = context_module::instance($this->database->cmid);
98 $this->cm = get_coursemodule_from_instance('data', $this->database->id);
9fac7c86
JL
99
100 // Create users.
cefd780f
JP
101 $this->student1 = self::getDataGenerator()->create_user(['firstname' => 'Olivia', 'lastname' => 'Smith']);
102 $this->student2 = self::getDataGenerator()->create_user(['firstname' => 'Ezra', 'lastname' => 'Johnson']);
103 $this->student3 = self::getDataGenerator()->create_user(['firstname' => 'Amelia', 'lastname' => 'Williams']);
104 $this->teacher = self::getDataGenerator()->create_user(['firstname' => 'Asher', 'lastname' => 'Jones']);
9fac7c86
JL
105
106 // Users enrolments.
107 $this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
108 $this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
109 $this->getDataGenerator()->enrol_user($this->student1->id, $this->course->id, $this->studentrole->id, 'manual');
110 $this->getDataGenerator()->enrol_user($this->student2->id, $this->course->id, $this->studentrole->id, 'manual');
ef6aea9d 111 $this->getDataGenerator()->enrol_user($this->student3->id, $this->course->id, $this->studentrole->id, 'manual');
9fac7c86 112 $this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
ef6aea9d
JL
113
114 $this->group1 = $this->getDataGenerator()->create_group(array('courseid' => $this->course->id));
115 $this->group2 = $this->getDataGenerator()->create_group(array('courseid' => $this->course->id));
116 groups_add_member($this->group1, $this->student1);
117 groups_add_member($this->group1, $this->student2);
118 groups_add_member($this->group2, $this->student3);
9fac7c86
JL
119 }
120
067b3fda
JL
121 /**
122 * Test get databases by courses
123 */
124 public function test_mod_data_get_databases_by_courses() {
125 global $DB;
126
127 $this->resetAfterTest(true);
128
129 // Create users.
130 $student = self::getDataGenerator()->create_user();
131 $teacher = self::getDataGenerator()->create_user();
132
133 // Set to the student user.
134 self::setUser($student);
135
136 // Create courses to add the modules.
137 $course1 = self::getDataGenerator()->create_course();
138 $course2 = self::getDataGenerator()->create_course();
139
140 // First database.
141 $record = new stdClass();
142 $record->introformat = FORMAT_HTML;
143 $record->course = $course1->id;
144 $database1 = self::getDataGenerator()->create_module('data', $record);
145
146 // Second database.
147 $record = new stdClass();
148 $record->introformat = FORMAT_HTML;
149 $record->course = $course2->id;
150 $database2 = self::getDataGenerator()->create_module('data', $record);
151
152 $studentrole = $DB->get_record('role', array('shortname' => 'student'));
153 $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
154
155 // Users enrolments.
156 $this->getDataGenerator()->enrol_user($student->id, $course1->id, $studentrole->id, 'manual');
157 $this->getDataGenerator()->enrol_user($teacher->id, $course1->id, $teacherrole->id, 'manual');
158
159 // Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
160 $enrol = enrol_get_plugin('manual');
161 $enrolinstances = enrol_get_instances($course2->id, true);
162 foreach ($enrolinstances as $courseenrolinstance) {
163 if ($courseenrolinstance->enrol == "manual") {
164 $instance2 = $courseenrolinstance;
165 break;
166 }
167 }
168 $enrol->enrol_user($instance2, $student->id, $studentrole->id);
169
170 // Create what we expect to be returned when querying the two courses.
171 // First for the student user.
172 $expectedfields = array('id', 'coursemodule', 'course', 'name', 'comments', 'timeavailablefrom',
173 'timeavailableto', 'timeviewfrom', 'timeviewto', 'requiredentries', 'requiredentriestoview',
f97305b0
JL
174 'intro', 'introformat', 'introfiles', 'maxentries', 'rssarticles', 'singletemplate', 'listtemplate',
175 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate',
176 'csstemplate', 'jstemplate', 'asearchtemplate', 'approval', 'defaultsort', 'defaultsortdir', 'manageapproved');
067b3fda
JL
177
178 // Add expected coursemodule.
179 $database1->coursemodule = $database1->cmid;
7ef49bd3 180 $database1->introfiles = [];
067b3fda 181 $database2->coursemodule = $database2->cmid;
7ef49bd3 182 $database2->introfiles = [];
067b3fda
JL
183
184 $expected1 = array();
185 $expected2 = array();
186 foreach ($expectedfields as $field) {
f97305b0
JL
187 if ($field == 'approval' or $field == 'manageapproved') {
188 $database1->{$field} = (bool) $database1->{$field};
189 $database2->{$field} = (bool) $database2->{$field};
190 }
067b3fda
JL
191 $expected1[$field] = $database1->{$field};
192 $expected2[$field] = $database2->{$field};
193 }
8352aa50
JL
194 $expected1['comments'] = (bool) $expected1['comments'];
195 $expected2['comments'] = (bool) $expected2['comments'];
067b3fda
JL
196
197 $expecteddatabases = array();
198 $expecteddatabases[] = $expected2;
199 $expecteddatabases[] = $expected1;
200
201 // Call the external function passing course ids.
202 $result = mod_data_external::get_databases_by_courses(array($course2->id, $course1->id));
8352aa50 203 $result = external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
067b3fda
JL
204 $this->assertEquals($expecteddatabases, $result['databases']);
205
206 // Call the external function without passing course id.
207 $result = mod_data_external::get_databases_by_courses();
8352aa50 208 $result = external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
067b3fda
JL
209 $this->assertEquals($expecteddatabases, $result['databases']);
210
211 // Unenrol user from second course and alter expected databases.
212 $enrol->unenrol_user($instance2, $student->id);
213 array_shift($expecteddatabases);
214
215 // Call the external function without passing course id.
216 $result = mod_data_external::get_databases_by_courses();
8352aa50 217 $result = external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
067b3fda
JL
218 $this->assertEquals($expecteddatabases, $result['databases']);
219
220 // Call for the second course we unenrolled the user from, expected warning.
221 $result = mod_data_external::get_databases_by_courses(array($course2->id));
222 $this->assertCount(1, $result['warnings']);
8352aa50 223 $this->assertEquals('1', $result['warnings'][0]['warningcode']);
067b3fda
JL
224 $this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
225
226 // Now, try as a teacher for getting all the additional fields.
227 self::setUser($teacher);
228
f97305b0 229 $additionalfields = array('scale', 'assessed', 'assesstimestart', 'assesstimefinish', 'editany', 'notification', 'timemodified');
067b3fda
JL
230
231 foreach ($additionalfields as $field) {
f97305b0
JL
232 if ($field == 'editany') {
233 $database1->{$field} = (bool) $database1->{$field};
8352aa50 234 }
f97305b0 235 $expecteddatabases[0][$field] = $database1->{$field};
067b3fda
JL
236 }
237 $result = mod_data_external::get_databases_by_courses();
8352aa50
JL
238 $result = external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
239 $this->assertEquals($expecteddatabases, $result['databases']);
240
241 // Admin should get all the information.
242 self::setAdminUser();
243
244 $result = mod_data_external::get_databases_by_courses(array($course1->id));
245 $result = external_api::clean_returnvalue(mod_data_external::get_databases_by_courses_returns(), $result);
067b3fda
JL
246 $this->assertEquals($expecteddatabases, $result['databases']);
247 }
9fac7c86
JL
248
249 /**
250 * Test view_database invalid id.
251 */
252 public function test_view_database_invalid_id() {
253
254 // Test invalid instance id.
cefd780f 255 $this->expectException('moodle_exception');
9fac7c86
JL
256 mod_data_external::view_database(0);
257 }
258
259 /**
260 * Test view_database not enrolled user.
261 */
262 public function test_view_database_not_enrolled_user() {
263
264 $usernotenrolled = self::getDataGenerator()->create_user();
265 $this->setUser($usernotenrolled);
266
cefd780f 267 $this->expectException('moodle_exception');
9fac7c86
JL
268 mod_data_external::view_database(0);
269 }
270
271 /**
272 * Test view_database no capabilities.
273 */
274 public function test_view_database_no_capabilities() {
275 // Test user with no capabilities.
276 // We need a explicit prohibit since this capability is allowed for students by default.
277 assign_capability('mod/data:viewpage', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
278 accesslib_clear_all_caches_for_unit_testing();
279
cefd780f 280 $this->expectException('moodle_exception');
9fac7c86
JL
281 mod_data_external::view_database(0);
282 }
283
284 /**
285 * Test view_database.
286 */
287 public function test_view_database() {
288
289 // Test user with full capabilities.
290 $this->setUser($this->student1);
291
292 // Trigger and capture the event.
293 $sink = $this->redirectEvents();
294
cefd780f 295 $result = mod_data_external::view_database($this->database->id);
9fac7c86
JL
296 $result = external_api::clean_returnvalue(mod_data_external::view_database_returns(), $result);
297
298 $events = $sink->get_events();
299 $this->assertCount(1, $events);
300 $event = array_shift($events);
301
302 // Checking that the event contains the expected values.
303 $this->assertInstanceOf('\mod_data\event\course_module_viewed', $event);
304 $this->assertEquals($this->context, $event->get_context());
305 $moodledata = new \moodle_url('/mod/data/view.php', array('id' => $this->cm->id));
306 $this->assertEquals($moodledata, $event->get_url());
307 $this->assertEventContextNotUsed($event);
308 $this->assertNotEmpty($event->get_name());
309 }
cac43b9b
JL
310
311 /**
312 * Test get_data_access_information for student.
313 */
314 public function test_get_data_access_information_student() {
315 global $DB;
316 // Modify the database to add access restrictions.
cefd780f
JP
317 $this->database->timeavailablefrom = time() + DAYSECS;
318 $this->database->requiredentries = 2;
319 $this->database->requiredentriestoview = 2;
320 $DB->update_record('data', $this->database);
cac43b9b
JL
321
322 // Test user with full capabilities.
323 $this->setUser($this->student1);
324
cefd780f 325 $result = mod_data_external::get_data_access_information($this->database->id);
cac43b9b
JL
326 $result = external_api::clean_returnvalue(mod_data_external::get_data_access_information_returns(), $result);
327
ef6aea9d 328 $this->assertEquals($this->group1->id, $result['groupid']);
cac43b9b
JL
329
330 $this->assertFalse($result['canmanageentries']);
331 $this->assertFalse($result['canapprove']);
332 $this->assertTrue($result['canaddentry']); // It return true because it doen't check time restrictions.
333 $this->assertFalse($result['timeavailable']);
334 $this->assertFalse($result['inreadonlyperiod']);
335 $this->assertEquals(0, $result['numentries']);
cefd780f
JP
336 $this->assertEquals($this->database->requiredentries, $result['entrieslefttoadd']);
337 $this->assertEquals($this->database->requiredentriestoview, $result['entrieslefttoview']);
cac43b9b
JL
338 }
339
340 /**
341 * Test get_data_access_information for teacher.
342 */
343 public function test_get_data_access_information_teacher() {
344 global $DB;
345 // Modify the database to add access restrictions.
cefd780f
JP
346 $this->database->timeavailablefrom = time() + DAYSECS;
347 $this->database->requiredentries = 2;
348 $this->database->requiredentriestoview = 2;
349 $DB->update_record('data', $this->database);
cac43b9b
JL
350
351 // Test user with full capabilities.
352 $this->setUser($this->teacher);
353
cefd780f 354 $result = mod_data_external::get_data_access_information($this->database->id);
cac43b9b
JL
355 $result = external_api::clean_returnvalue(mod_data_external::get_data_access_information_returns(), $result);
356
357 $this->assertEquals(0, $result['groupid']);
358
359 $this->assertTrue($result['canmanageentries']);
360 $this->assertTrue($result['canapprove']);
361 $this->assertTrue($result['canaddentry']); // It return true because it doen't check time restrictions.
362 $this->assertTrue($result['timeavailable']);
363 $this->assertFalse($result['inreadonlyperiod']);
364 $this->assertEquals(0, $result['numentries']);
365 $this->assertEquals(0, $result['entrieslefttoadd']);
366 $this->assertEquals(0, $result['entrieslefttoview']);
367 }
ef6aea9d
JL
368
369 /**
370 * Helper method to populate the database with some entries.
371 *
372 * @return array the entry ids created
373 */
374 public function populate_database_with_entries() {
375 global $DB;
376
771effef 377 // Force approval.
cefd780f 378 $DB->set_field('data', 'approval', 1, array('id' => $this->database->id));
ef6aea9d
JL
379 $generator = $this->getDataGenerator()->get_plugin_generator('mod_data');
380 $fieldtypes = array('checkbox', 'date', 'menu', 'multimenu', 'number', 'radiobutton', 'text', 'textarea', 'url');
381
382 $count = 1;
383 // Creating test Fields with default parameter values.
384 foreach ($fieldtypes as $fieldtype) {
385 $fieldname = 'field-' . $count;
386 $record = new StdClass();
387 $record->name = $fieldname;
388 $record->type = $fieldtype;
389 $record->required = 1;
390
cefd780f 391 $generator->create_field($record, $this->database);
ef6aea9d
JL
392 $count++;
393 }
394 // Get all the fields created.
cefd780f 395 $fields = $DB->get_records('data_fields', array('dataid' => $this->database->id), 'id');
ef6aea9d
JL
396
397 // Populate with contents, creating a new entry.
398 $contents = array();
399 $contents[] = array('opt1', 'opt2', 'opt3', 'opt4');
400 $contents[] = '01-01-2037'; // It should be lower than 2038, to avoid failing on 32-bit windows.
401 $contents[] = 'menu1';
402 $contents[] = array('multimenu1', 'multimenu2', 'multimenu3', 'multimenu4');
403 $contents[] = '12345';
404 $contents[] = 'radioopt1';
405 $contents[] = 'text for testing';
406 $contents[] = '<p>text area testing<br /></p>';
407 $contents[] = array('example.url', 'sampleurl');
408 $count = 0;
409 $fieldcontents = array();
410 foreach ($fields as $fieldrecord) {
411 $fieldcontents[$fieldrecord->id] = $contents[$count++];
412 }
413
414 $this->setUser($this->student1);
cefd780f 415 $entry11 = $generator->create_entry($this->database, $fieldcontents, $this->group1->id);
ef6aea9d 416 $this->setUser($this->student2);
cefd780f
JP
417 $entry12 = $generator->create_entry($this->database, $fieldcontents, $this->group1->id);
418 $entry13 = $generator->create_entry($this->database, $fieldcontents, $this->group1->id);
ef6aea9d
JL
419
420 $this->setUser($this->student3);
cefd780f 421 $entry21 = $generator->create_entry($this->database, $fieldcontents, $this->group2->id);
771effef
JL
422
423 // Approve all except $entry13.
424 $DB->set_field('data_records', 'approved', 1, ['id' => $entry11]);
425 $DB->set_field('data_records', 'approved', 1, ['id' => $entry12]);
426 $DB->set_field('data_records', 'approved', 1, ['id' => $entry21]);
427
428 return [$entry11, $entry12, $entry13, $entry21];
ef6aea9d
JL
429 }
430
431 /**
432 * Test get_entries
433 */
434 public function test_get_entries() {
435 global $DB;
771effef 436 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
ef6aea9d
JL
437
438 // First of all, expect to see only my group entries (not other users in other groups ones).
439 $this->setUser($this->student1);
cefd780f 440 $result = mod_data_external::get_entries($this->database->id);
ef6aea9d
JL
441 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
442 $this->assertCount(0, $result['warnings']);
443 $this->assertCount(2, $result['entries']);
444 $this->assertEquals(2, $result['totalcount']);
445 $this->assertEquals($entry11, $result['entries'][0]['id']);
446 $this->assertEquals($this->student1->id, $result['entries'][0]['userid']);
447 $this->assertEquals($this->group1->id, $result['entries'][0]['groupid']);
cefd780f 448 $this->assertEquals($this->database->id, $result['entries'][0]['dataid']);
ef6aea9d
JL
449 $this->assertEquals($entry12, $result['entries'][1]['id']);
450 $this->assertEquals($this->student2->id, $result['entries'][1]['userid']);
451 $this->assertEquals($this->group1->id, $result['entries'][1]['groupid']);
cefd780f 452 $this->assertEquals($this->database->id, $result['entries'][1]['dataid']);
ef6aea9d
JL
453 // Other user in same group.
454 $this->setUser($this->student2);
cefd780f 455 $result = mod_data_external::get_entries($this->database->id);
ef6aea9d
JL
456 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
457 $this->assertCount(0, $result['warnings']);
771effef
JL
458 $this->assertCount(3, $result['entries']); // I can see my entry not approved yet.
459 $this->assertEquals(3, $result['totalcount']);
ef6aea9d
JL
460
461 // Now try with the user in the second group that must see only one entry.
462 $this->setUser($this->student3);
cefd780f 463 $result = mod_data_external::get_entries($this->database->id);
ef6aea9d
JL
464 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
465 $this->assertCount(0, $result['warnings']);
466 $this->assertCount(1, $result['entries']);
467 $this->assertEquals(1, $result['totalcount']);
468 $this->assertEquals($entry21, $result['entries'][0]['id']);
469 $this->assertEquals($this->student3->id, $result['entries'][0]['userid']);
470 $this->assertEquals($this->group2->id, $result['entries'][0]['groupid']);
cefd780f 471 $this->assertEquals($this->database->id, $result['entries'][0]['dataid']);
ef6aea9d
JL
472
473 // Now, as teacher we should see all (we have permissions to view all groups).
474 $this->setUser($this->teacher);
cefd780f 475 $result = mod_data_external::get_entries($this->database->id);
ef6aea9d
JL
476 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
477 $this->assertCount(0, $result['warnings']);
771effef
JL
478 $this->assertCount(4, $result['entries']); // I can see the not approved one.
479 $this->assertEquals(4, $result['totalcount']);
ef6aea9d 480
cefd780f 481 $entries = $DB->get_records('data_records', array('dataid' => $this->database->id), 'id');
771effef 482 $this->assertCount(4, $entries);
ef6aea9d
JL
483 $count = 0;
484 foreach ($entries as $entry) {
485 $this->assertEquals($entry->id, $result['entries'][$count]['id']);
486 $count++;
487 }
488
489 // Basic test passing the parameter (instead having to calculate it).
490 $this->setUser($this->student1);
cefd780f 491 $result = mod_data_external::get_entries($this->database->id, $this->group1->id);
ef6aea9d
JL
492 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
493 $this->assertCount(0, $result['warnings']);
494 $this->assertCount(2, $result['entries']);
495 $this->assertEquals(2, $result['totalcount']);
496
497 // Test ordering (reverse).
498 $this->setUser($this->student1);
cefd780f 499 $result = mod_data_external::get_entries($this->database->id, $this->group1->id, false, null, 'DESC');
ef6aea9d
JL
500 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
501 $this->assertCount(0, $result['warnings']);
502 $this->assertCount(2, $result['entries']);
503 $this->assertEquals(2, $result['totalcount']);
504 $this->assertEquals($entry12, $result['entries'][0]['id']);
505
506 // Test pagination.
507 $this->setUser($this->student1);
cefd780f 508 $result = mod_data_external::get_entries($this->database->id, $this->group1->id, false, null, null, 0, 1);
ef6aea9d
JL
509 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
510 $this->assertCount(0, $result['warnings']);
511 $this->assertCount(1, $result['entries']);
512 $this->assertEquals(2, $result['totalcount']);
513 $this->assertEquals($entry11, $result['entries'][0]['id']);
514
cefd780f 515 $result = mod_data_external::get_entries($this->database->id, $this->group1->id, false, null, null, 1, 1);
ef6aea9d
JL
516 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
517 $this->assertCount(0, $result['warnings']);
518 $this->assertCount(1, $result['entries']);
519 $this->assertEquals(2, $result['totalcount']);
520 $this->assertEquals($entry12, $result['entries'][0]['id']);
521
522 // Now test the return contents.
cefd780f
JP
523 data_generate_default_template($this->database, 'listtemplate', 0, false, true); // Generate a default list template.
524 $result = mod_data_external::get_entries($this->database->id, $this->group1->id, true, null, null, 0, 2);
ef6aea9d
JL
525 $result = external_api::clean_returnvalue(mod_data_external::get_entries_returns(), $result);
526 $this->assertCount(0, $result['warnings']);
527 $this->assertCount(2, $result['entries']);
528 $this->assertEquals(2, $result['totalcount']);
529 $this->assertCount(9, $result['entries'][0]['contents']);
530 $this->assertCount(9, $result['entries'][1]['contents']);
531 // Search for some content.
532 $this->assertTrue(strpos($result['listviewcontents'], 'opt1') !== false);
533 $this->assertTrue(strpos($result['listviewcontents'], 'January') !== false);
534 $this->assertTrue(strpos($result['listviewcontents'], 'menu1') !== false);
535 $this->assertTrue(strpos($result['listviewcontents'], 'text for testing') !== false);
536 $this->assertTrue(strpos($result['listviewcontents'], 'sampleurl') !== false);
537 }
771effef
JL
538
539 /**
540 * Test get_entry_visible_groups.
541 */
542 public function test_get_entry_visible_groups() {
543 global $DB;
544
545 $DB->set_field('course', 'groupmode', VISIBLEGROUPS, ['id' => $this->course->id]);
546 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
547
548 // Check I can see my approved group entries.
549 $this->setUser($this->student1);
550 $result = mod_data_external::get_entry($entry11);
551 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
552 $this->assertCount(0, $result['warnings']);
553 $this->assertEquals($entry11, $result['entry']['id']);
554 $this->assertTrue($result['entry']['approved']);
555 $this->assertTrue($result['entry']['canmanageentry']); // Is mine, I can manage it.
556
557 // Entry from other group.
558 $result = mod_data_external::get_entry($entry21);
559 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
560 $this->assertCount(0, $result['warnings']);
561 $this->assertEquals($entry21, $result['entry']['id']);
562 }
563
564 /**
565 * Test get_entry_separated_groups.
566 */
567 public function test_get_entry_separated_groups() {
568 global $DB;
569 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
570
571 // Check I can see my approved group entries.
572 $this->setUser($this->student1);
573 $result = mod_data_external::get_entry($entry11);
574 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
575 $this->assertCount(0, $result['warnings']);
576 $this->assertEquals($entry11, $result['entry']['id']);
577 $this->assertTrue($result['entry']['approved']);
578 $this->assertTrue($result['entry']['canmanageentry']); // Is mine, I can manage it.
579
580 // Retrieve contents.
cefd780f 581 data_generate_default_template($this->database, 'singletemplate', 0, false, true);
771effef
JL
582 $result = mod_data_external::get_entry($entry11, true);
583 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
584 $this->assertCount(0, $result['warnings']);
585 $this->assertCount(9, $result['entry']['contents']);
586 $this->assertTrue(strpos($result['entryviewcontents'], 'opt1') !== false);
587 $this->assertTrue(strpos($result['entryviewcontents'], 'January') !== false);
588 $this->assertTrue(strpos($result['entryviewcontents'], 'menu1') !== false);
589 $this->assertTrue(strpos($result['entryviewcontents'], 'text for testing') !== false);
590 $this->assertTrue(strpos($result['entryviewcontents'], 'sampleurl') !== false);
591
592 // This is in my group but I'm not the author.
593 $result = mod_data_external::get_entry($entry12);
594 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
595 $this->assertCount(0, $result['warnings']);
596 $this->assertEquals($entry12, $result['entry']['id']);
597 $this->assertTrue($result['entry']['approved']);
598 $this->assertFalse($result['entry']['canmanageentry']); // Not mine.
599
600 $this->setUser($this->student3);
601 $result = mod_data_external::get_entry($entry21);
602 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
603 $this->assertCount(0, $result['warnings']);
604 $this->assertEquals($entry21, $result['entry']['id']);
605 $this->assertTrue($result['entry']['approved']);
606 $this->assertTrue($result['entry']['canmanageentry']); // Is mine, I can manage it.
607
608 // As teacher I should be able to see all the entries.
609 $this->setUser($this->teacher);
610 $result = mod_data_external::get_entry($entry11);
611 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
612 $this->assertEquals($entry11, $result['entry']['id']);
613
614 $result = mod_data_external::get_entry($entry12);
615 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
616 $this->assertEquals($entry12, $result['entry']['id']);
617 // This is the not approved one.
618 $result = mod_data_external::get_entry($entry13);
619 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
620 $this->assertEquals($entry13, $result['entry']['id']);
621
622 $result = mod_data_external::get_entry($entry21);
623 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
624 $this->assertEquals($entry21, $result['entry']['id']);
625
626 // Now, try to get an entry not approved yet.
627 $this->setUser($this->student1);
628 $this->expectException('moodle_exception');
629 $result = mod_data_external::get_entry($entry13);
630 }
631
632 /**
633 * Test get_entry from other group in separated groups.
634 */
635 public function test_get_entry_other_group_separated_groups() {
636 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
637
638 // We should not be able to view other gropu entries (in separated groups).
639 $this->setUser($this->student1);
640 $this->expectException('moodle_exception');
641 $result = mod_data_external::get_entry($entry21);
642 }
a934c896
JL
643
644 /**
645 * Test get_fields.
646 */
647 public function test_get_fields() {
648 global $DB;
649 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
650
651 $this->setUser($this->student1);
cefd780f 652 $result = mod_data_external::get_fields($this->database->id);
a934c896
JL
653 $result = external_api::clean_returnvalue(mod_data_external::get_fields_returns(), $result);
654
655 // Basically compare we retrieve all the fields and the correct values.
cefd780f 656 $fields = $DB->get_records('data_fields', array('dataid' => $this->database->id), 'id');
a934c896
JL
657 foreach ($result['fields'] as $field) {
658 $this->assertEquals($field, (array) $fields[$field['id']]);
659 }
660 }
56b8edcb 661
84c2a87b
JL
662 /**
663 * Test get_fields_database_without_fields.
664 */
665 public function test_get_fields_database_without_fields() {
666
667 $this->setUser($this->student1);
668 $result = mod_data_external::get_fields($this->database->id);
669 $result = external_api::clean_returnvalue(mod_data_external::get_fields_returns(), $result);
670
671 $this->assertEmpty($result['fields']);
672 }
673
56b8edcb
JL
674 /**
675 * Test search_entries.
676 */
677 public function test_search_entries() {
678 global $DB;
679 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
680
56b8edcb 681 $this->setUser($this->student1);
6cf2ab73
JL
682 // Empty search, it should return all the visible entries.
683 $result = mod_data_external::search_entries($this->database->id, 0, false);
684 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
685 $this->assertCount(2, $result['entries']);
686 $this->assertEquals(2, $result['totalcount']);
687
688 // Search for something that does not exists.
689 $result = mod_data_external::search_entries($this->database->id, 0, false, 'abc');
690 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
691 $this->assertCount(0, $result['entries']);
692 $this->assertEquals(0, $result['totalcount']);
693
694 // Search by text matching all the entries.
cefd780f 695 $result = mod_data_external::search_entries($this->database->id, 0, false, 'text');
56b8edcb
JL
696 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
697 $this->assertCount(2, $result['entries']);
698 $this->assertEquals(2, $result['totalcount']);
be4bdab7 699 $this->assertEquals(2, $result['maxcount']);
56b8edcb
JL
700
701 // Now as the other student I should receive my not approved entry. Apply ordering here.
702 $this->setUser($this->student2);
cefd780f 703 $result = mod_data_external::search_entries($this->database->id, 0, false, 'text', [], DATA_APPROVED, 'ASC');
56b8edcb
JL
704 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
705 $this->assertCount(3, $result['entries']);
706 $this->assertEquals(3, $result['totalcount']);
be4bdab7 707 $this->assertEquals(3, $result['maxcount']);
56b8edcb
JL
708 // The not approved one should be the first.
709 $this->assertEquals($entry13, $result['entries'][0]['id']);
710
711 // Now as the other group student.
712 $this->setUser($this->student3);
cefd780f 713 $result = mod_data_external::search_entries($this->database->id, 0, false, 'text');
56b8edcb
JL
714 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
715 $this->assertCount(1, $result['entries']);
716 $this->assertEquals(1, $result['totalcount']);
be4bdab7 717 $this->assertEquals(1, $result['maxcount']);
56b8edcb
JL
718 $this->assertEquals($this->student3->id, $result['entries'][0]['userid']);
719
720 // Same normal text search as teacher.
721 $this->setUser($this->teacher);
cefd780f 722 $result = mod_data_external::search_entries($this->database->id, 0, false, 'text');
56b8edcb
JL
723 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
724 $this->assertCount(4, $result['entries']); // I can see all groups and non approved.
725 $this->assertEquals(4, $result['totalcount']);
be4bdab7 726 $this->assertEquals(4, $result['maxcount']);
56b8edcb
JL
727
728 // Pagination.
729 $this->setUser($this->teacher);
cefd780f 730 $result = mod_data_external::search_entries($this->database->id, 0, false, 'text', [], DATA_TIMEADDED, 'ASC', 0, 2);
56b8edcb
JL
731 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
732 $this->assertCount(2, $result['entries']); // Only 2 per page.
733 $this->assertEquals(4, $result['totalcount']);
be4bdab7 734 $this->assertEquals(4, $result['maxcount']);
56b8edcb
JL
735
736 // Now advanced search or not dinamic fields (user firstname for example).
737 $this->setUser($this->student1);
738 $advsearch = [
739 ['name' => 'fn', 'value' => json_encode($this->student2->firstname)]
740 ];
cefd780f 741 $result = mod_data_external::search_entries($this->database->id, 0, false, '', $advsearch);
56b8edcb
JL
742 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
743 $this->assertCount(1, $result['entries']);
744 $this->assertEquals(1, $result['totalcount']);
be4bdab7 745 $this->assertEquals(2, $result['maxcount']);
56b8edcb
JL
746 $this->assertEquals($this->student2->id, $result['entries'][0]['userid']); // I only found mine!
747
748 // Advanced search for fields.
749 $field = $DB->get_record('data_fields', array('type' => 'url'));
750 $advsearch = [
751 ['name' => 'f_' . $field->id , 'value' => 'sampleurl']
752 ];
cefd780f 753 $result = mod_data_external::search_entries($this->database->id, 0, false, '', $advsearch);
56b8edcb
JL
754 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
755 $this->assertCount(2, $result['entries']); // Found two entries matching this.
756 $this->assertEquals(2, $result['totalcount']);
be4bdab7 757 $this->assertEquals(2, $result['maxcount']);
56b8edcb
JL
758
759 // Combined search.
760 $field2 = $DB->get_record('data_fields', array('type' => 'number'));
761 $advsearch = [
762 ['name' => 'f_' . $field->id , 'value' => 'sampleurl'],
763 ['name' => 'f_' . $field2->id , 'value' => '12345'],
764 ['name' => 'ln', 'value' => json_encode($this->student2->lastname)]
765 ];
cefd780f 766 $result = mod_data_external::search_entries($this->database->id, 0, false, '', $advsearch);
56b8edcb
JL
767 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
768 $this->assertCount(1, $result['entries']); // Only one matching everything.
769 $this->assertEquals(1, $result['totalcount']);
be4bdab7 770 $this->assertEquals(2, $result['maxcount']);
56b8edcb
JL
771
772 // Combined search (no results).
773 $field2 = $DB->get_record('data_fields', array('type' => 'number'));
774 $advsearch = [
775 ['name' => 'f_' . $field->id , 'value' => 'sampleurl'],
776 ['name' => 'f_' . $field2->id , 'value' => '98780333'], // Non existent number.
777 ];
cefd780f 778 $result = mod_data_external::search_entries($this->database->id, 0, false, '', $advsearch);
56b8edcb
JL
779 $result = external_api::clean_returnvalue(mod_data_external::search_entries_returns(), $result);
780 $this->assertCount(0, $result['entries']); // Only one matching everything.
781 $this->assertEquals(0, $result['totalcount']);
be4bdab7 782 $this->assertEquals(2, $result['maxcount']);
56b8edcb 783 }
229158fe
JL
784
785 /**
786 * Test approve_entry.
787 */
788 public function test_approve_entry() {
789 global $DB;
790 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
791
792 $this->setUser($this->teacher);
793 $this->assertEquals(0, $DB->get_field('data_records', 'approved', array('id' => $entry13)));
794 $result = mod_data_external::approve_entry($entry13);
795 $result = external_api::clean_returnvalue(mod_data_external::approve_entry_returns(), $result);
796 $this->assertEquals(1, $DB->get_field('data_records', 'approved', array('id' => $entry13)));
797 }
798
799 /**
800 * Test unapprove_entry.
801 */
802 public function test_unapprove_entry() {
803 global $DB;
804 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
805
806 $this->setUser($this->teacher);
807 $this->assertEquals(1, $DB->get_field('data_records', 'approved', array('id' => $entry11)));
808 $result = mod_data_external::approve_entry($entry11, false);
809 $result = external_api::clean_returnvalue(mod_data_external::approve_entry_returns(), $result);
810 $this->assertEquals(0, $DB->get_field('data_records', 'approved', array('id' => $entry11)));
811 }
812
813 /**
814 * Test approve_entry missing permissions.
815 */
816 public function test_approve_entry_missing_permissions() {
817 global $DB;
818 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
819
820 $this->setUser($this->student1);
821 $this->expectException('moodle_exception');
822 mod_data_external::approve_entry($entry13);
823 }
67bb168e
JL
824
825 /**
826 * Test delete_entry as teacher. Check I can delete any entry.
827 */
828 public function test_delete_entry_as_teacher() {
829 global $DB;
830 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
831
832 $this->setUser($this->teacher);
833 $result = mod_data_external::delete_entry($entry11);
834 $result = external_api::clean_returnvalue(mod_data_external::delete_entry_returns(), $result);
835 $this->assertEquals(0, $DB->count_records('data_records', array('id' => $entry11)));
836
837 // Entry in other group.
838 $result = mod_data_external::delete_entry($entry21);
839 $result = external_api::clean_returnvalue(mod_data_external::delete_entry_returns(), $result);
840 $this->assertEquals(0, $DB->count_records('data_records', array('id' => $entry21)));
841 }
842
843 /**
844 * Test delete_entry as student. Check I can delete my own entries.
845 */
846 public function test_delete_entry_as_student() {
847 global $DB;
848 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
849
850 $this->setUser($this->student1);
851 $result = mod_data_external::delete_entry($entry11);
852 $result = external_api::clean_returnvalue(mod_data_external::delete_entry_returns(), $result);
853 $this->assertEquals(0, $DB->count_records('data_records', array('id' => $entry11)));
854 }
855
856 /**
857 * Test delete_entry as student in read only mode period. Check I cannot delete my own entries in that period.
858 */
859 public function test_delete_entry_as_student_in_read_only_period() {
860 global $DB;
861 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
862 // Set a time period.
cefd780f
JP
863 $this->database->timeviewfrom = time() - HOURSECS;
864 $this->database->timeviewto = time() + HOURSECS;
865 $DB->update_record('data', $this->database);
67bb168e
JL
866
867 $this->setUser($this->student1);
868 $this->expectException('moodle_exception');
869 mod_data_external::delete_entry($entry11);
870 }
871
872 /**
873 * Test delete_entry with an user missing permissions.
874 */
875 public function test_delete_entry_missing_permissions() {
876 global $DB;
877 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
878
879 $this->setUser($this->student1);
880 $this->expectException('moodle_exception');
881 mod_data_external::delete_entry($entry21);
882 }
61c640c1
JL
883
884 /**
885 * Test add_entry.
886 */
887 public function test_add_entry() {
888 global $DB;
889 // First create the record structure and add some entries.
890 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
891
892 $this->setUser($this->student1);
893 $newentrydata = [];
cefd780f 894 $fields = $DB->get_records('data_fields', array('dataid' => $this->database->id), 'id');
61c640c1
JL
895 // Prepare the new entry data.
896 foreach ($fields as $field) {
897 $subfield = $value = '';
898
899 switch ($field->type) {
900 case 'checkbox':
901 $value = ['opt1', 'opt2'];
902 break;
903 case 'date':
904 // Add two extra.
905 $newentrydata[] = [
906 'fieldid' => $field->id,
907 'subfield' => 'day',
908 'value' => json_encode('5')
909 ];
910 $newentrydata[] = [
911 'fieldid' => $field->id,
912 'subfield' => 'month',
913 'value' => json_encode('1')
914 ];
915 $subfield = 'year';
916 $value = '1981';
917 break;
918 case 'menu':
919 $value = 'menu1';
920 break;
921 case 'multimenu':
922 $value = ['multimenu1', 'multimenu4'];
923 break;
924 case 'number':
925 $value = 6;
926 break;
927 case 'radiobutton':
928 $value = 'radioopt1';
929 break;
930 case 'text':
931 $value = 'some text';
932 break;
933 case 'textarea':
934 $newentrydata[] = [
935 'fieldid' => $field->id,
936 'subfield' => 'content1',
937 'value' => json_encode(FORMAT_MOODLE)
938 ];
939 $newentrydata[] = [
940 'fieldid' => $field->id,
941 'subfield' => 'itemid',
942 'value' => json_encode(0)
943 ];
944 $value = 'more text';
945 break;
946 case 'url':
947 $value = 'https://moodle.org';
948 $subfield = 0;
949 break;
950 }
951
952 $newentrydata[] = [
953 'fieldid' => $field->id,
954 'subfield' => $subfield,
955 'value' => json_encode($value)
956 ];
957 }
cefd780f 958 $result = mod_data_external::add_entry($this->database->id, 0, $newentrydata);
61c640c1
JL
959 $result = external_api::clean_returnvalue(mod_data_external::add_entry_returns(), $result);
960
961 $newentryid = $result['newentryid'];
b0f3e6d6 962 $result = mod_data_external::get_entry($newentryid, true);
61c640c1
JL
963 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
964 $this->assertEquals($this->student1->id, $result['entry']['userid']);
965 $this->assertCount(9, $result['entry']['contents']);
966 foreach ($result['entry']['contents'] as $content) {
967 $field = $fields[$content['fieldid']];
968 // Stored content same that the one retrieved by WS.
969 $dbcontent = $DB->get_record('data_content', array('fieldid' => $field->id, 'recordid' => $newentryid));
970 $this->assertEquals($dbcontent->content, $content['content']);
971
972 // Now double check everything stored is correct.
973 if ($field->type == 'checkbox') {
974 $this->assertEquals('opt1##opt2', $content['content']);
975 continue;
976 }
977 if ($field->type == 'date') {
978 $this->assertEquals(347500800, $content['content']); // Date in gregorian format.
979 continue;
980 }
981 if ($field->type == 'menu') {
982 $this->assertEquals('menu1', $content['content']);
983 continue;
984 }
985 if ($field->type == 'multimenu') {
986 $this->assertEquals('multimenu1##multimenu4', $content['content']);
987 continue;
988 }
989 if ($field->type == 'number') {
990 $this->assertEquals(6, $content['content']);
991 continue;
992 }
993 if ($field->type == 'radiobutton') {
994 $this->assertEquals('radioopt1', $content['content']);
995 continue;
996 }
997 if ($field->type == 'text') {
998 $this->assertEquals('some text', $content['content']);
999 continue;
1000 }
1001 if ($field->type == 'textarea') {
1002 $this->assertEquals('more text', $content['content']);
1003 $this->assertEquals(FORMAT_MOODLE, $content['content1']);
1004 continue;
1005 }
1006 if ($field->type == 'url') {
1007 $this->assertEquals('https://moodle.org', $content['content']);
1008 continue;
1009 }
1010 $this->assertEquals('multimenu1##multimenu4', $content['content']);
1011 }
1012
1013 // Now, try to add another entry but removing some required data.
1014 unset($newentrydata[0]);
cefd780f 1015 $result = mod_data_external::add_entry($this->database->id, 0, $newentrydata);
61c640c1
JL
1016 $result = external_api::clean_returnvalue(mod_data_external::add_entry_returns(), $result);
1017 $this->assertEquals(0, $result['newentryid']);
1018 $this->assertCount(0, $result['generalnotifications']);
1019 $this->assertCount(1, $result['fieldnotifications']);
1020 $this->assertEquals('field-1', $result['fieldnotifications'][0]['fieldname']);
1021 $this->assertEquals(get_string('errormustsupplyvalue', 'data'), $result['fieldnotifications'][0]['notification']);
1022 }
1023
1024 /**
1025 * Test add_entry empty_form.
1026 */
1027 public function test_add_entry_empty_form() {
cefd780f 1028 $result = mod_data_external::add_entry($this->database->id, 0, []);
61c640c1
JL
1029 $result = external_api::clean_returnvalue(mod_data_external::add_entry_returns(), $result);
1030 $this->assertEquals(0, $result['newentryid']);
1031 $this->assertCount(1, $result['generalnotifications']);
1032 $this->assertCount(0, $result['fieldnotifications']);
1033 $this->assertEquals(get_string('emptyaddform', 'data'), $result['generalnotifications'][0]);
1034 }
1035
1036 /**
1037 * Test add_entry read_only_period.
1038 */
1039 public function test_add_entry_read_only_period() {
1040 global $DB;
1041 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1042 // Set a time period.
cefd780f
JP
1043 $this->database->timeviewfrom = time() - HOURSECS;
1044 $this->database->timeviewto = time() + HOURSECS;
1045 $DB->update_record('data', $this->database);
61c640c1
JL
1046
1047 $this->setUser($this->student1);
1048 $this->expectExceptionMessage(get_string('noaccess', 'data'));
1049 $this->expectException('moodle_exception');
cefd780f 1050 mod_data_external::add_entry($this->database->id, 0, []);
61c640c1
JL
1051 }
1052
1053 /**
1054 * Test add_entry max_num_entries.
1055 */
1056 public function test_add_entry_max_num_entries() {
1057 global $DB;
1058 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1059 // Set a time period.
cefd780f
JP
1060 $this->database->maxentries = 1;
1061 $DB->update_record('data', $this->database);
61c640c1
JL
1062
1063 $this->setUser($this->student1);
1064 $this->expectExceptionMessage(get_string('noaccess', 'data'));
1065 $this->expectException('moodle_exception');
cefd780f 1066 mod_data_external::add_entry($this->database->id, 0, []);
61c640c1 1067 }
4ca2890d
JL
1068
1069 /**
1070 * Test update_entry.
1071 */
1072 public function test_update_entry() {
1073 global $DB;
1074 // First create the record structure and add some entries.
1075 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1076
1077 $this->setUser($this->student1);
1078 $newentrydata = [];
cefd780f 1079 $fields = $DB->get_records('data_fields', array('dataid' => $this->database->id), 'id');
4ca2890d
JL
1080 // Prepare the new entry data.
1081 foreach ($fields as $field) {
1082 $subfield = $value = '';
1083
1084 switch ($field->type) {
1085 case 'checkbox':
1086 $value = ['opt1', 'opt2'];
1087 break;
1088 case 'date':
1089 // Add two extra.
1090 $newentrydata[] = [
1091 'fieldid' => $field->id,
1092 'subfield' => 'day',
1093 'value' => json_encode('5')
1094 ];
1095 $newentrydata[] = [
1096 'fieldid' => $field->id,
1097 'subfield' => 'month',
1098 'value' => json_encode('1')
1099 ];
1100 $subfield = 'year';
1101 $value = '1981';
1102 break;
1103 case 'menu':
1104 $value = 'menu1';
1105 break;
1106 case 'multimenu':
1107 $value = ['multimenu1', 'multimenu4'];
1108 break;
1109 case 'number':
1110 $value = 6;
1111 break;
1112 case 'radiobutton':
1113 $value = 'radioopt2';
1114 break;
1115 case 'text':
1116 $value = 'some text';
1117 break;
1118 case 'textarea':
1119 $newentrydata[] = [
1120 'fieldid' => $field->id,
1121 'subfield' => 'content1',
1122 'value' => json_encode(FORMAT_MOODLE)
1123 ];
1124 $newentrydata[] = [
1125 'fieldid' => $field->id,
1126 'subfield' => 'itemid',
1127 'value' => json_encode(0)
1128 ];
1129 $value = 'more text';
1130 break;
1131 case 'url':
1132 $value = 'https://moodle.org';
1133 $subfield = 0;
1134 break;
1135 }
1136
1137 $newentrydata[] = [
1138 'fieldid' => $field->id,
1139 'subfield' => $subfield,
1140 'value' => json_encode($value)
1141 ];
1142 }
1143 $result = mod_data_external::update_entry($entry11, $newentrydata);
1144 $result = external_api::clean_returnvalue(mod_data_external::update_entry_returns(), $result);
1145 $this->assertTrue($result['updated']);
1146 $this->assertCount(0, $result['generalnotifications']);
1147 $this->assertCount(0, $result['fieldnotifications']);
1148
b0f3e6d6 1149 $result = mod_data_external::get_entry($entry11, true);
4ca2890d
JL
1150 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
1151 $this->assertEquals($this->student1->id, $result['entry']['userid']);
1152 $this->assertCount(9, $result['entry']['contents']);
1153 foreach ($result['entry']['contents'] as $content) {
1154 $field = $fields[$content['fieldid']];
1155 // Stored content same that the one retrieved by WS.
1156 $dbcontent = $DB->get_record('data_content', array('fieldid' => $field->id, 'recordid' => $entry11));
1157 $this->assertEquals($dbcontent->content, $content['content']);
1158
1159 // Now double check everything stored is correct.
1160 if ($field->type == 'checkbox') {
1161 $this->assertEquals('opt1##opt2', $content['content']);
1162 continue;
1163 }
1164 if ($field->type == 'date') {
1165 $this->assertEquals(347500800, $content['content']); // Date in gregorian format.
1166 continue;
1167 }
1168 if ($field->type == 'menu') {
1169 $this->assertEquals('menu1', $content['content']);
1170 continue;
1171 }
1172 if ($field->type == 'multimenu') {
1173 $this->assertEquals('multimenu1##multimenu4', $content['content']);
1174 continue;
1175 }
1176 if ($field->type == 'number') {
1177 $this->assertEquals(6, $content['content']);
1178 continue;
1179 }
1180 if ($field->type == 'radiobutton') {
1181 $this->assertEquals('radioopt2', $content['content']);
1182 continue;
1183 }
1184 if ($field->type == 'text') {
1185 $this->assertEquals('some text', $content['content']);
1186 continue;
1187 }
1188 if ($field->type == 'textarea') {
1189 $this->assertEquals('more text', $content['content']);
1190 $this->assertEquals(FORMAT_MOODLE, $content['content1']);
1191 continue;
1192 }
1193 if ($field->type == 'url') {
1194 $this->assertEquals('https://moodle.org', $content['content']);
1195 continue;
1196 }
1197 $this->assertEquals('multimenu1##multimenu4', $content['content']);
1198 }
1199
1200 // Now, try to update the entry but removing some required data.
1201 unset($newentrydata[0]);
1202 $result = mod_data_external::update_entry($entry11, $newentrydata);
1203 $result = external_api::clean_returnvalue(mod_data_external::update_entry_returns(), $result);
1204 $this->assertFalse($result['updated']);
1205 $this->assertCount(0, $result['generalnotifications']);
1206 $this->assertCount(1, $result['fieldnotifications']);
1207 $this->assertEquals('field-1', $result['fieldnotifications'][0]['fieldname']);
1208 $this->assertEquals(get_string('errormustsupplyvalue', 'data'), $result['fieldnotifications'][0]['notification']);
1209 }
1210
1211 /**
1212 * Test update_entry sending empty data.
1213 */
1214 public function test_update_entry_empty_data() {
1215 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1216
1217 $this->setUser($this->student1);
1218 $result = mod_data_external::update_entry($entry11, []);
1219 $result = external_api::clean_returnvalue(mod_data_external::update_entry_returns(), $result);
1220 $this->assertFalse($result['updated']);
1221 $this->assertCount(1, $result['generalnotifications']);
1222 $this->assertCount(9, $result['fieldnotifications']);
1223 $this->assertEquals(get_string('emptyaddform', 'data'), $result['generalnotifications'][0]);
1224 }
1225
1226 /**
1227 * Test update_entry in read only period.
1228 */
1229 public function test_update_entry_read_only_period() {
1230 global $DB;
1231 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1232 // Set a time period.
cefd780f
JP
1233 $this->database->timeviewfrom = time() - HOURSECS;
1234 $this->database->timeviewto = time() + HOURSECS;
1235 $DB->update_record('data', $this->database);
4ca2890d
JL
1236
1237 $this->setUser($this->student1);
1238 $this->expectExceptionMessage(get_string('noaccess', 'data'));
1239 $this->expectException('moodle_exception');
1240 mod_data_external::update_entry($entry11, []);
1241 }
1242
1243 /**
1244 * Test update_entry other_user.
1245 */
1246 public function test_update_entry_other_user() {
1247 // Try to update other user entry.
1248 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1249 $this->setUser($this->student2);
1250 $this->expectExceptionMessage(get_string('noaccess', 'data'));
1251 $this->expectException('moodle_exception');
1252 mod_data_external::update_entry($entry11, []);
1253 }
26d8bcea
JL
1254
1255 /**
1256 * Test get_entry_rating_information.
1257 */
1258 public function test_get_entry_rating_information() {
1259 global $DB, $CFG;
1260 require_once($CFG->dirroot . '/rating/lib.php');
1261
1262 $DB->set_field('data', 'assessed', RATING_AGGREGATE_SUM, array('id' => $this->database->id));
1263 $DB->set_field('data', 'scale', 100, array('id' => $this->database->id));
1264 list($entry11, $entry12, $entry13, $entry21) = self::populate_database_with_entries();
1265
1266 $user1 = self::getDataGenerator()->create_user();
1267 $user2 = self::getDataGenerator()->create_user();
1268 $this->getDataGenerator()->enrol_user($user1->id, $this->course->id, $this->studentrole->id, 'manual');
1269 $this->getDataGenerator()->enrol_user($user2->id, $this->course->id, $this->studentrole->id, 'manual');
1270
1271 // Rate the entry as user1.
1272 $rating1 = new stdClass();
1273 $rating1->contextid = $this->context->id;
1274 $rating1->component = 'mod_data';
1275 $rating1->ratingarea = 'entry';
1276 $rating1->itemid = $entry11;
1277 $rating1->rating = 50;
1278 $rating1->scaleid = 100;
1279 $rating1->userid = $user1->id;
1280 $rating1->timecreated = time();
1281 $rating1->timemodified = time();
1282 $rating1->id = $DB->insert_record('rating', $rating1);
1283
1284 // Rate the entry as user2.
1285 $rating2 = new stdClass();
1286 $rating2->contextid = $this->context->id;
1287 $rating2->component = 'mod_data';
1288 $rating2->ratingarea = 'entry';
1289 $rating2->itemid = $entry11;
1290 $rating2->rating = 100;
1291 $rating2->scaleid = 100;
1292 $rating2->userid = $user2->id;
1293 $rating2->timecreated = time() + 1;
1294 $rating2->timemodified = time() + 1;
1295 $rating2->id = $DB->insert_record('rating', $rating2);
1296
1297 // As student, retrieve ratings information.
1298 $this->setUser($this->student2);
1299 $result = mod_data_external::get_entry($entry11);
1300 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
1301 $this->assertCount(1, $result['ratinginfo']['ratings']);
1302 $this->assertFalse($result['ratinginfo']['ratings'][0]['canviewaggregate']);
1303 $this->assertFalse($result['ratinginfo']['canviewall']);
1304 $this->assertFalse($result['ratinginfo']['ratings'][0]['canrate']);
1305 $this->assertTrue(!isset($result['ratinginfo']['ratings'][0]['count']));
1306
1307 // Now, as teacher, I should see the info correctly.
1308 $this->setUser($this->teacher);
1309 $result = mod_data_external::get_entry($entry11);
1310 $result = external_api::clean_returnvalue(mod_data_external::get_entry_returns(), $result);
1311 $this->assertCount(1, $result['ratinginfo']['ratings']);
1312 $this->assertTrue($result['ratinginfo']['ratings'][0]['canviewaggregate']);
1313 $this->assertTrue($result['ratinginfo']['canviewall']);
1314 $this->assertTrue($result['ratinginfo']['ratings'][0]['canrate']);
1315 $this->assertEquals(2, $result['ratinginfo']['ratings'][0]['count']);
1316 $this->assertEquals(100, $result['ratinginfo']['ratings'][0]['aggregate']); // Expect maximium scale value.
1317 }
067b3fda 1318}