Compare commits

..

221 Commits

Author SHA1 Message Date
Jun Pataleta e8d03fdae4 Moodle release 4.1.10 2024-04-20 15:57:26 +08:00
Huong Nguyen c8922328b2 weekly release 4.1.9+ 2024-04-19 17:05:41 +07:00
Laurent David 19635ef720 MDL-81267 mod_data: Additional tests 2024-04-17 10:33:42 +02:00
Laurent David 9d5a4746ab MDL-81267 mod_data: Clean field type before inclusion
* Filter out wrong field types when restoring or creating a field.
2024-04-17 10:33:42 +02:00
Stevani Andolo e4406472f0 MDL-81354 core: Escape string of fullname 2024-04-12 11:30:23 +00:00
Paul Holden cf2f67272a MDL-81062 mod_lesson: escape identity fields in overview report. 2024-04-12 11:30:23 +00:00
Paul Holden 2ebac5604c MDL-80712 mod_workshop: stricter cleaning of sub-plugin values. 2024-04-12 11:30:23 +00:00
Paul Holden c5f48698da MDL-81058 admin: fix sesskey checks for admin preset actions. 2024-04-12 11:30:23 +00:00
Paul Holden c2a043f50d MDL-81059 tool_analytics: fix sesskey checks for model actions. 2024-04-12 11:30:23 +00:00
Laurent David 001c78285f MDL-81284 mod_wiki: Add stricter cleaning of contentformat
* When restoring backup we clean the contentformat and defaultformat
to avoid issue with invalid value.
* Add tests for format and defaultformat so to check that we
 filter out invalid formats
* Remove private $basepath variable as it was used one and not always
initialised correctly.
2024-04-12 11:30:23 +00:00
meirzamoodle af90bb572e MDL-81352 filter: Ensure equation safety prior to filtering 2024-04-12 11:30:23 +00:00
Paul Holden 882a660f7e MDL-81135 mod_feedback: stricter cleaning of item type parameter. 2024-04-12 11:30:23 +00:00
Huong Nguyen adc1de569d MDL-81247 calendar: Extra validation for webservices 2024-04-12 11:30:23 +00:00
Paul Holden 607716f206 MDL-81247 calendar: freeze event type if "user" only allowed. 2024-04-12 11:30:23 +00:00
Leon Stringer 5358ce28ee MDL-80585 report_log: sanitize descriptions
Strip any HTML tags from values in the "Description" column.
2024-04-12 11:30:23 +00:00
Sara Arjona fef8dda150 weekly release 4.1.9+ 2024-04-12 13:23:37 +02:00
Ilya Tregubov b049731dfb Merge branch 'MDL-80385-401' of https://github.com/paulholden/moodle into MOODLE_401_STABLE 2024-04-11 15:43:31 +08:00
Huong Nguyen 5277dca108 Merge branch 'MDL-81362-401' of https://github.com/ssj365/moodle into MOODLE_401_STABLE 2024-04-11 11:00:21 +07:00
Ilya Tregubov 4be4d0d489 Merge branch 'MDL-81491-401' of https://github.com/snake/moodle into MOODLE_401_STABLE 2024-04-11 09:51:19 +08:00
Shamiso.Jaravaza 3d0bcb7172 MDL-81362 mod_bigbluebuttonbn: Fix content type 2024-04-10 11:49:39 -06:00
Sara Arjona 7dac3707fd Merge branch 'MDL-74977-401' of https://github.com/HuongNV13/moodle into MOODLE_401_STABLE 2024-04-10 15:51:10 +02:00
Huong Nguyen 037a7d5d6c MDL-74977 core_courseformat: add expanded section update actions
This also fix the Random "Course content preferences" Behat failure
2024-04-10 18:12:45 +07:00
Jake Dallimore f5587cf881 MDL-81491 enrol_lti: fix incorrect login_hint parameter type validation
This was always bad, but since we only used it to verify the existence
of the param, and let library code take $_REQUEST for the real
validation, it was ok. Now, since we're redirecting to self during
necessary cookie checks added by MDL-80835, we lose the real value
originally stored in $_REQUEST. This patch just fixes the param type,
setting it to raw, which is what it should have used originally. The
raw value won't be cast from a string to an int as part of the
require_param call, so the value won't be lost any more.
2024-04-10 17:45:07 +08:00
Sara Arjona a18c0b7c8b weekly release 4.1.9+ 2024-04-09 12:07:33 +02:00
Jake Dallimore 097a879e1a Merge branch 'MDL-81060-401-fix' of https://github.com/meirzamoodle/moodle into MOODLE_401_STABLE 2024-04-09 10:14:07 +08:00
Jake Dallimore 1901cd3fdf Merge branch 'MDL-81405-401' of https://github.com/jleyva/moodle into MOODLE_401_STABLE 2024-04-08 15:35:46 +08:00
Jake Dallimore 2c9a5c009f MDL-81060 core: fix incorrect userquota usage in zip_packer
This change reverts much of MDL-74641, removing the erroneous userquota
checks from zip_packer. Now, during extraction, the zip_packer will exit
with an error status when it encounters a file which is larger than its
advertised size, and NOT when it determines the size of the extracted
files have exceeded the userquota (which only applies to private files
and which was used incorrectly here). It also reverts changes to the
draftfiles_ajax.php file, restoring the original (pre-MDL-74641) error
handling.
2024-04-08 09:11:26 +07:00
Juan Leyva 179bfdf5c5 MDL-81405 tool_mobile: Set Partitioned cookie when required 2024-04-06 12:31:50 +02:00
Juan Leyva eb975467bd MDL-81405 session: New core cookie helper utility class 2024-04-06 12:31:50 +02:00
Sara Arjona 5efbd6e0e1 weekly release 4.1.9+ 2024-04-02 14:46:54 +02:00
Andrew Nicols fa20b1790f Merge branch 'MDL-79712-401' of https://github.com/snake/moodle into MOODLE_401_STABLE 2024-04-02 11:57:12 +08:00
Jake Dallimore 7d579dd4bb MDL-79712 auth_lti: ensure MoodleSession uses SameSite=None Secure
The MoodleSession cookie is already set this way when using Chrome, but
not for Firefox. This is a decision made in \core\session\manager. When
Firefox eventually defaults to SameSite=Lax when the SameSite attribute
is omitted from the Set-Cookie headers, the MoodleSession cookie won't
be sent. This change ensures the cookies used during LTI launches will
continue to work if/when this happens, and despite any changes which may
be made to core's sessionlib in future.
2024-04-02 11:44:28 +08:00
Ilya Tregubov 6b0661b9ea Merge branch 'MDL-80036-401' of https://github.com/mickhawkins/moodle into MOODLE_401_STABLE 2024-03-27 11:08:55 +08:00
Sara Arjona afd57ca9a0 weekly release 4.1.9+ 2024-03-26 12:31:21 +01:00
Huong Nguyen c14e75a017 Merge branch 'MDL-81353-401' of https://github.com/snake/moodle into MOODLE_401_STABLE 2024-03-26 10:34:46 +07:00
Jake Dallimore 318e2344c0 MDL-81353 auth_lti: fix str_contains usage in cookie_helper
This failure was being masked by Symfony\Polyfill\Php80 during unit
tests.
2024-03-26 09:28:01 +08:00
Sara Arjona 17ed404ccc weekly release 4.1.9+ 2024-03-22 14:03:06 +01:00
Huong Nguyen 5b54a87858 Merge branch 'MDL-80835-401' of https://github.com/snake/moodle into MOODLE_401_STABLE 2024-03-21 14:54:20 +07:00
Jake Dallimore ea49be1e61 MDL-80835 auth_lti: fix bad cast breaking samesite LTI usage 2024-03-21 15:41:16 +08:00
Jake Dallimore 0f3d3b2d77 MDL-80835 enrol_lti: add partitioning support for OIDC state cookie
Adds the property that is required by Chrome to opt-in to its 3rd party
cookie partitioning solution, CHIPS. This specific change ensures the
'state' cookie, used in the OIDC handshake, has partitioning support.
This cookie can be partitioned unconditionally, since it's a cookie
controlled by the library and one we don't expect to be set without
partitioning elsewhere.
2024-03-21 15:41:16 +08:00
Jake Dallimore dee41e0648 MDL-80835 auth_lti: add partitioning to post-auth MoodleSession cookie
Adds the property that is required by Chrome to opt-in to its 3rd party
cookie partitioning solution, CHIPS. This specific change to auth_lti is
to ensure the MoodleSession Set-Cookie header resulting from
complete_user_login() calls (in auth.php) have this property set.
2024-03-21 15:41:16 +08:00
Jake Dallimore c11b1c6b3f MDL-80835 enrol_lti: add cookies required notice to auth login endpoint
This will be displayed if the cookie checks fail, which currently occurs
in Safari only.
2024-03-21 15:41:16 +08:00
Jake Dallimore e2362b0a7a MDL-80835 enrol_lti: add partitioning support to MoodleSession cookie
Adds the property that is required by Chrome to opt-in to its 3rd party
cookie partitioning solution, CHIPS. This specific change deals with the
cookie that is set when the user is not yet auth'd with the site and is
necessary to facilitate OIDC nonce retrieval and validation.
2024-03-21 15:41:15 +08:00
Jake Dallimore d63721cb15 MDL-80835 auth_lti: add cookie helper facilitating CHIPS opt-in
To opt a cookie in to Chrome's 3rd party cookie partitioning solution,
CHIPS, the property 'Partitioned;' needs to be set. This adds a helper
class supporting this, for a given cookie(s).

Note also, PHP's native
cookie APIs (setcookie, etc) don't support this cookie property yet -
(https://github.com/php/php-src/issues/12646).

Since this class is intended to allow existing Set-Cookie headers to be
modified before being sent (e.g. allowing clients to set a property on a
cookie set elsewhere in code), it deals with the headers directly anyway
but it means that new cookies must also use this helper to opt-in,
instead of relying on setcookie(). E.g. where the intent is to add
partitioning support to a new cookie, that cookie must first be set
(setcookie) and then it may opt-in to partitioning via this helper;
partitioning support cannot be achieved directly through setcookie and
friends yet.
2024-03-21 15:41:14 +08:00
Ilya Tregubov 66b1733bda weekly release 4.1.9+ 2024-03-20 08:54:22 +08:00
Ilya Tregubov 81821e6833 Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-03-20 08:54:18 +08:00
Michael Hawkins 965a5fdb27 MDL-80036 core: Update security.txt expiry 2024-03-19 15:31:33 +08:00
Huong Nguyen 6aa2828161 Merge branch 'MDL-81156-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-03-19 10:56:15 +07:00
Andrew Nicols d46a37ebd4 Merge branch 'MDL-77255-401' of https://github.com/HuongNV13/moodle into MOODLE_401_STABLE 2024-03-19 11:40:21 +08:00
Huong Nguyen 8c358aefd9 MDL-77255 block_tag_flickr: Update to match with the new API
Flickr dropped php_serial format, we need to change to JSON format
2024-03-19 10:14:58 +07:00
AMOS bot 40aceb0256 Automatically generated installer lang files 2024-03-19 00:08:44 +00:00
Huong Nguyen f64240ce94 weekly release 4.1.9+ 2024-03-15 21:48:28 +07:00
Huong Nguyen 10c7926c0f Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-03-15 21:48:28 +07:00
Jake Dallimore 8a26315686 Merge branch 'MDL-80167-401-int' of https://github.com/HuongNV13/moodle into MOODLE_401_STABLE 2024-03-15 12:55:15 +08:00
Huong Nguyen 0e8d4d8e2a MDL-80167 core: Skip Oracle for Oracle environment in unit tests 2024-03-15 08:46:44 +07:00
Sara Arjona 5ac11701ac Merge branch 'MDL-80167-401' of https://github.com/HuongNV13/moodle into MOODLE_401_STABLE 2024-03-14 11:55:12 +01:00
Sara Arjona dc65317ba6 Merge branch 'MDL-80479-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-03-14 11:48:14 +01:00
Huong Nguyen f0ae7c4343 MDL-80167 admin: Add environment check for Oracle database 2024-03-14 17:42:51 +07:00
Simey Lameze b52c1855fa MDL-80479 behat: improve new test for quiz timer 2024-03-14 10:21:29 +08:00
Angelia Dela Cruz 6e1e63cc6b MDL-80479 mod_quiz: Behat to set quiz opening and closing time 2024-03-14 10:21:29 +08:00
Simey Lameze 50ae525be9 MDL-81156 behat: coverage for force course language 2024-03-14 09:04:49 +08:00
AMOS bot a700d119df Merge branch 'MOODLE_401_STABLE' into install_401_STABLE 2024-03-14 00:13:07 +00:00
Dale Davies 9ccd794b36 MDL-80385 core: Check lock state before attempting to acquire a lock
This is a cherry-pick of the same change from MDL-76865, which was
accidentally reverted in MDL-79428.
2024-03-13 13:56:49 +00:00
AMOS bot 49673645ea Automatically generated installer lang files 2024-03-13 00:11:01 +00:00
Ilya Tregubov e6316e6b9b weekly release 4.1.9+ 2024-03-13 08:10:00 +08:00
Huong Nguyen 5003afbe48 Merge branch 'MDL-76805-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-03-12 10:33:02 +07:00
Shamiso.Jaravaza 7e1bbaaf20 MDL-76805 mod_bigbluebuttonbn: Fix up behat tests 2024-03-12 11:08:28 +08:00
Sara Arjona d1111bc3e8 weekly release 4.1.9+ 2024-03-08 11:12:04 +01:00
Huong Nguyen 8de03684ac Merge branch 'MDL-79990-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-03-07 10:05:09 +07:00
Simey Lameze 2db07c4d0a MDL-79990 behat: custom step to verify assign grading data
This commit also optimise the new behat test.
2024-03-07 09:44:34 +08:00
Angelia Dela Cruz 3ac3d942dd MDL-79990 gradingform: Behat test for marking guide information display 2024-03-07 09:44:34 +08:00
Huong Nguyen 84308c7dfc Merge branch 'MDL-79278-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-03-06 09:13:39 +07:00
Angelia Dela Cruz 24a0e76ebf MDL-79278 mod_quiz: Teacher can set how quiz questions behave behat
Co-authored-by: Simey Lameze <simey@moodle.com>
2024-03-06 09:48:46 +08:00
Sara Arjona 2444b2b787 weekly release 4.1.9+ 2024-03-05 11:22:31 +01:00
Jun Pataleta b704fa7dda Merge branch 'MDL-80819_401' of https://github.com/stronk7/moodle into MOODLE_401_STABLE 2024-03-05 11:48:39 +08:00
Huong Nguyen 9d3d193f29 Merge branch 'MDL-80836-401' of https://github.com/snake/moodle into MOODLE_401_STABLE 2024-03-05 10:24:39 +07:00
Jun Pataleta 43c7557e84 weekly release 4.1.9+ 2024-03-01 12:24:39 +08:00
Jun Pataleta da74ac4987 Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-03-01 12:24:37 +08:00
AMOS bot 1e5bc3a393 Automatically generated installer lang files 2024-02-28 00:10:59 +00:00
Sara Arjona 7c20cd1b81 Merge branch 'MDL-81036-401' of https://github.com/marinaglancy/moodle into MOODLE_401_STABLE 2024-02-27 13:04:19 +01:00
Marina Glancy edf1a1ac8c MDL-81036 behat: fix the action menu clickable area selector 2024-02-23 11:23:21 +00:00
Eloy Lafuente (stronk7) 5a2acac1ed MDL-80819 install: halt any install if php min version is not met
Apart from environmental stuff, the moodle_minimum_php_version_is_met()
function is executed by all installs (web, cli, database, ...)
and halts any installation (early) not meeting the PHP constraints.
2024-02-23 11:08:40 +01:00
Huong Nguyen 719c95009e weekly release 4.1.9+ 2024-02-23 08:37:56 +07:00
Huong Nguyen 860b4b941a Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-02-23 08:37:54 +07:00
Huong Nguyen 26ed48ec40 Merge branch 'MDL-80844_401' of https://github.com/stronk7/moodle into MOODLE_401_STABLE 2024-02-22 11:24:26 +07:00
Huong Nguyen 58ba1a9448 Merge branch 'MDL-80862-401' of https://github.com/andrewnicols/moodle into MOODLE_401_STABLE 2024-02-22 10:38:16 +07:00
Sara Arjona 40d2b4de39 Merge branch 'MDL-76441_401' of https://github.com/stronk7/moodle into MOODLE_401_STABLE 2024-02-21 17:50:08 +01:00
Sara Arjona bce1d7ff85 Merge branch 'MDL-80404-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-02-21 13:23:48 +01:00
Angelia Dela Cruz 3f439ff9d4 MDL-80404 mod_data: Behat for url autolinking and opening in new window 2024-02-21 16:03:46 +08:00
Huong Nguyen 0c34355c85 Merge branch 'MDL-79792-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-02-21 14:25:55 +07:00
Angelia Dela Cruz ab118d48f5 MDL-79792 core_badges: Behat test for awarding badge to group members 2024-02-21 14:06:09 +08:00
Jun Pataleta 6df3213c9b Merge branch 'MDL-79003-401' of https://github.com/andrewnicols/moodle into MOODLE_401_STABLE 2024-02-21 10:35:31 +08:00
Andrew Nicols 6dbd0e938f MDL-80862 testing: Reset task manager between behat tests 2024-02-20 10:55:04 +08:00
AMOS bot 8889f6f26f Automatically generated installer lang files 2024-02-20 00:13:48 +00:00
Sara Arjona 36aa09726b Merge branch 'MDL-79674-401' of https://github.com/junpataleta/moodle into MOODLE_401_STABLE 2024-02-19 10:20:59 +01:00
Sara Arjona 196c2ae7a5 Merge branch 'MDL-80613-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-02-19 09:14:39 +01:00
Sara Arjona 4d217e3a1a weekly release 4.1.9+ 2024-02-15 15:39:56 +01:00
Sara Arjona 09e3db1aa6 Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-02-15 15:39:53 +01:00
Simey Lameze 8815ecb3fd MDL-80613 behat: convert manual completion steps to use generators 2024-02-15 11:02:57 +08:00
Jake Dallimore 8482210209 MDL-80836 auth_lti: take user through login instead of sesspiggyback
Browsers are phasing out 3rd party cookies. Those which can be set are
partitioned to the top level embedding site, so piggybacking is
prevented. This will break the account linking process. This fix swaps
the piggyback for a login round trip, as originally intended, which
resolves the issue.
2024-02-15 10:40:05 +08:00
Sara Arjona 281ef7ef8d Merge branch 'MDL-79321-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-02-14 09:35:38 +01:00
Angelia Dela Cruz 6970580b4c MDL-79321 mod_quiz: Behat to set quiz as interactive with multiple tries 2024-02-13 17:09:00 +08:00
Jun Pataleta 652633b467 Merge branch 'MDL-80402-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-02-13 15:51:52 +08:00
Angelia Dela Cruz 5a7963d9f5 MDL-80402 mod_quiz: Behat for interactive quiz question dependency 2024-02-13 15:23:17 +08:00
AMOS bot 56ff5e78f1 Automatically generated installer lang files 2024-02-13 00:10:13 +00:00
Eloy Lafuente (stronk7) e31db928b5 MDL-80844 phpunit: Only some tests can use the debugging sink
The only tests that have COMPLETE* support for the debugging sink
are the advanced_testcase and the database_driver ones (store and
report). So we must ensure that the rest of tests don't use the
debugging sink at all.

Right now we are using it for storing, but later there is not
reporting, so any debugging happening within non advanced tests
is not detected.

This commit just ensures that we stop making that storing for
non advanced/database_driver tests. Nothing more, nothing less.

* Note that we have had to add a few missing bits to the
database_driver testcase because it was not 100% complete. Now
it behaves 100% the same than the advanced_testcase one regarding
the debugging sink.
2024-02-12 13:03:06 +01:00
AMOS bot 03fcd81892 Automatically generated installer lang files 2024-02-12 00:11:13 +00:00
Eloy Lafuente (stronk7) 05a41b6e32 MDL-76441 env: Moodle 4.2.x and 4.3.x do not support PHP 8.3 2024-02-10 12:15:11 +01:00
Jake Dallimore 8a38a37f1f Moodle release 4.1.9 2024-02-09 10:33:26 +08:00
Sara Arjona 4ea1bd3537 weekly release 4.1.8+ 2024-02-08 16:18:25 +01:00
Sara Arjona 35b7cbf027 Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-02-08 16:18:21 +01:00
Ilya Tregubov 87eb0fdf21 MDL-80504 forum: Fix seperate group mode 2024-02-08 10:56:42 +07:00
Andrew Nicols c8aef2e4ba Merge branch 'MDL-80738-401' of https://github.com/paulholden/moodle into MOODLE_401_STABLE 2024-02-08 11:39:18 +08:00
Leon Stringer fa72ebc155 MDL-80501 mod_h5pactivity: activity group mode
Respect activity's group mode when checking access to the report.
Previously only the course's group mode was checked.
2024-02-08 11:16:16 +08:00
Andrew Nicols 6d7f162df0 Merge branch 'MDL-80667-401' of https://github.com/paulholden/moodle into MOODLE_401_STABLE 2024-02-08 09:42:22 +08:00
Jun Pataleta 97d64fb809 Merge branch 'MDL-80784-401' of https://github.com/noeldemartin/moodle into MOODLE_401_STABLE 2024-02-07 17:19:53 +08:00
Paul Holden fd3c586992 MDL-80738 quiz_statistics: ensure tests uses a DB-backed lock class.
Fix the test file/class name too.

Co-authored-by: Andrew Nicols <andrew@nicols.co.uk>
2024-02-07 07:50:13 +00:00
Ilya Tregubov 61fb8ee988 MDL-69774 mod_forum: Restrict URL to accpet only expected params 2024-02-07 15:28:42 +08:00
Huong Nguyen 44f8c11123 Merge branch 'MDL-80512-401' of https://github.com/paulholden/moodle into MOODLE_401_STABLE 2024-02-07 13:32:01 +07:00
Jun Pataleta e5b9510af2 Merge branch 'MDL-75081-401' of https://github.com/junpataleta/moodle into MOODLE_401_STABLE 2024-02-07 10:38:03 +08:00
Paul Holden ab151f86ab MDL-75081 grade: fix rogue gradebook scenarios containing invalid steps. 2024-02-07 09:07:04 +08:00
Paul Holden e36e40f530 MDL-75081 behat: define new heading named selector.
Co-authored-by: Jun Pataleta <jun@moodle.com>
2024-02-07 09:06:40 +08:00
Paul Holden 3a8a8c8463 MDL-75081 behat: correct tests of table contents asserting one column.
Prior to this change, assertions of "should exist" and "should not
exist" in table content, where the step provided only a single column,
could give false positives and pass (when they shouldn't).
2024-02-07 09:05:07 +08:00
meirzamoodle 2f811e6acf MDL-74641 repository: Fix wrong increment of temporary file for small sizes 2024-02-06 16:00:21 +01:00
meirzamoodle fb7da9c74f MDL-74641 repository: Handles increase bytes while extracting zip files
We should not rely solely on the provided size information.
Therefore the system needs to recalculate the size of each file in the zip file,
whether small or big.

The changes also cover the filemanager.js file if an error appears.
2024-02-06 16:00:21 +01:00
meirzamoodle d27862e2ca MDL-78300 block: Determine if users can comment based on context 2024-02-06 16:00:21 +01:00
Paul Holden c7fde934c7 MDL-54749 tool_langimport: require sesskey to update lang packs. 2024-02-06 16:00:21 +01:00
Sara Arjona be50fbe20c Merge branch 'MDL-80816_401' of https://github.com/stronk7/moodle into MOODLE_401_STABLE 2024-02-06 15:51:56 +01:00
Ilya Tregubov 74bf7382dd Merge branch 'MDL-80713-401' of https://github.com/HuongNV13/moodle into MOODLE_401_STABLE 2024-02-06 11:20:38 +08:00
Huong Nguyen cb075f6257 MDL-80713 Unit Tests: Message sink improvement
- Added a new method called get_messages_by_component()
  This method will help to retreive the redirected messages
  of specific component only
- Added a new method called get_messages_by_component_and_type()
  This method will help to retreive the redirected messages
  of specific component and type only
2024-02-05 13:27:07 +07:00
Eloy Lafuente (stronk7) 8a1b5fc2b0 MDL-80816 core: Bump actions to newer versions
All the new ones are Nodejs 20 based, because
Nodejs 16 is being deprecated @ GH environments.

https://github.blog/changelog/2023-09-22-github-actions-transitioning-from-node-16-to-node-20
2024-02-02 17:17:53 +01:00
Noel De Martin bd22abe778 MDL-80784 behat: Disable SSL checks for app initialization 2024-01-31 14:06:17 +01:00
Jun Pataleta b3867e7422 MDL-79674 behat: Use proper tags for testing WCAG 2.1 criteria
`wcag2a` and `wcag2aa` refer to WCAG 2.0 standards. We should be using
`wcag21a` and `wcag21aa` to test against WCAG 2.1 standards.

See:
https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#axe-core-tags
2024-01-30 16:19:50 +08:00
Jun Pataleta 8c298f14bb MDL-79674 behat: axe-core version fixes
* Update \behat_accessibility::run_axe_validation_for_tags()'s
  PHPDoc block to reflect the current version.
* Fix incorrect copyright tag for the library
2024-01-30 16:19:48 +08:00
Andrew Nicols 58bd2ed8e4 MDL-79003 js: Bump stylelint and components
Stylelint 15 deprecates a heap of rules which will be removed in 16.

We can't use 16 because it's ESM and requires a big restructure of our
build process.

We can temporarily silence the deprecations and then when we update our
build tooling we can make use of @stylistic/stylelint-plugin to add the
rules back.

This commit:
- bumps stylelint and related dependencies accordingly
- fixes issues identified with newer sniffs
- temporarily silences deprecation warnings
2024-01-30 14:08:51 +08:00
Andrew Nicols 36ca488c06 MDL-79003 js: Move rollup ratelimit to generateBundle
There are two phases of a build: Building, and then Outputting.

We were previously listening on the final event for the build phase, but
we should be listening to the final event of the output phase.
2024-01-30 14:08:51 +08:00
Andrew Nicols bca28b03a9 MDL-79003 js: Move browserlist config to package.json 2024-01-30 14:08:51 +08:00
Andrew Nicols a6216bb890 MDL-79003 js: Standard package bump - glob 2024-01-30 14:08:20 +08:00
Andrew Nicols 94b14df11d MDL-79003 js: Standard package bump - async 2024-01-30 14:07:09 +08:00
Andrew Nicols 0dc60026c8 MDL-79003 js: Remove grunt-contrib-uglify
We stopped using this when we updated our processes to support ESMs in
MDL-62497. Removal of the dependency was missed at the time.
2024-01-30 14:07:08 +08:00
Andrew Nicols 63a1ec81c4 MDL-79003 js: Standard package bump - grunt 2024-01-30 14:07:08 +08:00
Andrew Nicols 150fc0837a MDL-79003 js: Standard package bump - watchman 2024-01-30 14:07:08 +08:00
Andrew Nicols 72958879c6 MDL-79003 js: Standard package bump - ajv 2024-01-30 14:07:08 +08:00
Andrew Nicols d8d560b7fe MDL-79003 js: Use our own jsdoc wrapper
grunt-jsdoc is abandoned and only works with an older version of jsdoc.

This is a very simple wrapper around jsdoc itself.

This commit also includes a fix for broken docs.
2024-01-30 14:07:06 +08:00
Andrew Nicols 917dd49db2 MDL-79003 core: Bump eslint 2024-01-30 14:04:40 +08:00
Ruslan Kabalin 80691cf5a3 MDL-79003 eslint: Enable 'reportUnusedDisableDirectives' eslint setting
This commit is a backport of MDL-74301 which should have been backported
at the time.

This will warn on unused /* eslint-disable */ statements.
2024-01-30 14:04:38 +08:00
Ruslan Kabalin e20720ce0e MDL-79003 eslint: Remove rules included in eslint:recommended
This commit is a backport of MDL-74301 which should have been backported
at the time.

All rules included in "eslint:recommended" set containing matching
values are removed from the list. Recommended set is defined in
node_modules/eslint/conf/eslint-recommended.js
2024-01-30 14:03:10 +08:00
Ruslan Kabalin f976349b95 MDL-79003 eslint: Remove deprecated rules.
This commit is a backport of MDL-74301 which should have been backported
at the time.

To identify deprecated rules, temporary install sarbbottam/eslint-find-rules, then run
`npx eslint-find-rules -d .eslintrc`, it will return a list of rules
defined in .eslintrc that were deprecated.
2024-01-30 14:03:09 +08:00
Ruslan Kabalin 312a166f1e MDL-79003 eslint: Refactor jsdoc rules.
This commit is a backport of MDL-74301 which should have been backported
at the time.

Adding 'plugin:promise/recommended' results in 5k+ jsdoc warnings most
of which includes missing return and naming preferences (e.g. 'returns'
over 'return' or 'string' over 'String'). This needs to be audited and
addressed seprately.
2024-01-30 14:03:09 +08:00
Ruslan Kabalin f16ca8fa7a MDL-79003 eslint: Use 'plugin:promise/recommended'
This commit is a backport of MDL-74301 which should have been backported
at the time.

This enables recommended rules and brings back related rules. Without
reducing level to warn for some of them, this gives numerous (about 88) issues mainly
catch-or-return. Recommended set is defined in
node_modules/eslint-plugin-promise/index.js
2024-01-30 14:03:09 +08:00
Ruslan Kabalin 846a8b6568 MDL-79003 eslint: Address issues reported by eslint
This commit is a backport of MDL-74301 which should have been backported
at the time.
2024-01-30 14:03:05 +08:00
Ruslan Kabalin 692d3090fa MDL-79003 eslint: Change configuration and use 'eslint:recommended'
This commit is a backport of MDL-74301 which should have been backported
at the time.
2024-01-30 13:33:40 +08:00
Ruslan Kabalin 8092eb95c4 MDL-79003 eslint: Upgrade eslint and babel
This commit is a backport of MDL-74301 which should have been backported
at the time.

This patch includes changes:
* Upgrade "@babel/core" to latest point release
* Remove plugins already included into current "@babel/preset-env":
  - "@babel/plugin-proposal-class-properties"
  - "@babel/plugin-proposal-json-strings"
  - "@babel/plugin-syntax-dynamic-import"
  - "@babel/plugin-syntax-import-meta"
* Upgrade "eslint" to latest version
* Replace "eslint-plugin-babel" (depreacted in 2019) with "@babel/eslint-parser" and "@babel/eslint-plugin"
2024-01-30 13:33:40 +08:00
Andrew Nicols 2b864ceec3 MDL-79003 core: Bump NodeJS to lts/iron (NodeJS 20) 2024-01-30 13:33:40 +08:00
AMOS bot 80083244b6 Automatically generated installer lang files 2024-01-27 00:11:24 +00:00
Sara Arjona 560f4d895b weekly release 4.1.8+ 2024-01-25 16:48:39 +01:00
Jun Pataleta 95c3017da4 Merge branch 'MDL-80656-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-01-25 12:13:47 +08:00
Ilya Tregubov 8fffc08ee8 Merge branch 'MDL-79159-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-01-25 09:36:26 +08:00
Ilya Tregubov 364230d6f8 Merge branch 'MDL-80653-401' of https://github.com/paulholden/moodle into MOODLE_401_STABLE 2024-01-25 09:26:49 +08:00
Paul Holden 45f674e8cb MDL-80653 h5p: handle content type creation errors in test.
See also same in c7d08f85.
2024-01-24 08:58:30 +00:00
Sara Arjona 4ba166cf80 Merge branch 'MDL-79940-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-01-24 09:22:48 +01:00
Angelia Dela Cruz 3a779663aa MDL-79159 mod_lesson: Behat coverage for lesson question max attempts 2024-01-24 16:18:46 +08:00
Simey Lameze ca7b24f6d0 MDL-80656 behat: remove unnecessary activity duplication steps 2024-01-24 11:14:42 +08:00
Angelia Dela Cruz 35a2a34a7d MDL-79940 mod_workshop: Behat to confirm review button for reviewers 2024-01-24 09:10:41 +08:00
Paul Holden 603c794190 MDL-80512 tool_task: absolute path to required library file. 2024-01-23 09:27:09 +00:00
Sara Arjona 38c4d51947 Merge branch 'MDL-80339-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-01-23 07:48:37 +01:00
Angelia Dela Cruz a86228f547 MDL-80339 mod_lesson: Behat to confirm grade visibility in lesson 2024-01-23 10:13:27 +08:00
Jun Pataleta b30033c6c0 Merge branch 'MDL-79029-401' of https://github.com/ferranrecio/moodle into MOODLE_401_STABLE 2024-01-23 09:21:26 +08:00
Ferran Recio 5661849a02 MDL-79029 behat: optimize behat tests
Replace some add activity to section steps to the new
add activity to course section so they are faster and do
not require javascript.
2024-01-22 11:23:44 +01:00
Ferran Recio 66e8ce9976 MDL-79029 behat: new add activity steps 2024-01-22 11:23:44 +01:00
Jun Pataleta cf92eaeb0b Merge branch 'MDL-80377-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-01-22 16:32:15 +08:00
Angelia Dela Cruz f7f40e54e6 MDL-80377 block: Behat confirming folder file in recent activity block 2024-01-19 14:31:30 +08:00
Huong Nguyen 627177855a weekly release 4.1.8+ 2024-01-19 11:24:39 +07:00
Paul Holden 8c7983a43f MDL-80667 task: preserve environment when running tasks from web.
For sites that rely on environment variables to set configuration,
ensure they are also present when executing task process.

Co-authored-by: Olivier Wenger <olivier.wenger@liip.ch>
2024-01-18 16:54:10 +00:00
Andrew Nicols 0d0aa11e19 Merge branch 'MDL-80591_401' of https://github.com/stronk7/moodle into MOODLE_401_STABLE 2024-01-18 10:57:43 +08:00
Sara Arjona eb0439b5da Merge branch 'MDL-80266-401' of https://github.com/andrewnicols/moodle into MOODLE_401_STABLE 2024-01-16 07:20:21 +01:00
Andrew Nicols 37101f0698 MDL-80266 mod_forum: Reset subscription caches between behat tests 2024-01-16 13:34:46 +08:00
Eloy Lafuente (stronk7) 4b8a001bb0 MDL-80591 phpunit: delegate run to phpunit binary
Instead of manually including composer's auto-loading
stuff and then run PHPUnit\TextUI\Command::main(), now
we are using the PHPUnit "binary".

That way behaviour should be 100% the same than
running vendor/bin/phpunit (recommended instead of util.php --run).

Also, note that, for other util.php commands, we still need
composer's auto-loading to happen, so we have moved it immediately
after the --run command.

Finally, a few more file_exists() conditions have been added
to ensure that PHPUnit is properly installed. Redundant but...
2024-01-13 18:32:43 +01:00
Ilya Tregubov a9cf9d5519 weekly release 4.1.8+ 2024-01-12 09:11:53 +08:00
Ilya Tregubov 53275e5b8f Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2024-01-12 09:11:48 +08:00
Huong Nguyen 518e5799e4 Merge branch 'MDL-80452-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-01-11 10:45:35 +07:00
Huong Nguyen 6a610605f6 Merge branch 'MDL-80229-401' of https://github.com/davewoloszyn/moodle into MOODLE_401_STABLE 2024-01-11 10:36:56 +07:00
Angelia Dela Cruz e4eb16bd9f MDL-80452 mod_h5pactivity: Behat for H5Pactivity duplication and delete 2024-01-11 11:22:22 +08:00
Huong Nguyen 3e831cc8c5 Merge branch 'MDL-73639-401-fix' of https://github.com/sarjona/moodle into MOODLE_401_STABLE 2024-01-10 14:47:48 +07:00
Sara Arjona 5ecca13a6f Merge branch 'MDL-80340-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-01-10 07:35:14 +01:00
Huong Nguyen 278f58dae0 Merge branch 'MDL-80382-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2024-01-10 10:31:13 +07:00
Sara Arjona 73cf6fb65c MDL-73639 behat: Fix the failure with the Enrol button
The button at the top of the page is hidden a few seconds by the
un-enrolment confirmation dialogue. Instead of waiting a few seconds
or reloading the page, the button at the bottom is clicked instead.
2024-01-09 16:39:38 +01:00
Simey Lameze 6483b5d68f MDL-80340 behat: make query to fetch h5p attempts less strict 2024-01-09 16:16:06 +08:00
Angelia Dela Cruz 6c24b8289f MDL-80382 behat: Replace "Frist" typos in Behat tests to "First" 2024-01-09 11:00:06 +08:00
Huong Nguyen e2e00a9dd4 Merge branch 'MDL-73639-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2024-01-08 16:10:15 +07:00
Simey Lameze 8168155e17 MDL-73639 behat: improvements to the new recover grades test 2024-01-08 13:09:25 +08:00
Angelia Dela Cruz d6650b63bf MDL-73639 core_grades: Behat to test Recover grades default settings 2024-01-08 13:09:25 +08:00
Ilya Tregubov 174389cc26 Merge branch 'MDL-79937-401_fixlessonmatching' of https://github.com/catalystfd/moodle into MOODLE_401_STABLE 2024-01-08 09:21:02 +08:00
AMOS bot 03454c2262 Automatically generated installer lang files 2023-12-23 00:11:20 +00:00
Jun Pataleta e591ddc4e8 Moodle release 4.1.8 2023-12-22 10:01:56 +08:00
Sara Arjona e1767fa80f weekly release 4.1.7+ 2023-12-21 13:34:33 +01:00
Huong Nguyen e25033e42d Merge branch 'MDL-80151-401' of https://github.com/lameze/moodle into MOODLE_401_STABLE 2023-12-20 15:40:30 +07:00
Huong Nguyen dd2c19eb09 MDL-80151 behat: Improve viewing site calendar step 2023-12-20 16:32:55 +08:00
Angelia Dela Cruz 3b8b8d7d84 MDL-80151 mod_chat: Behat for chat repeat times and past session view 2023-12-20 16:32:55 +08:00
Simey Lameze 5378285a9a MDL-80151 behat: add calendar step to navigate to specific view 2023-12-20 16:32:55 +08:00
Jun Pataleta 3a098250f1 Merge branch 'MDL-68124-401' of https://github.com/sarjona/moodle into MOODLE_401_STABLE 2023-12-20 15:01:28 +08:00
Jun Pataleta 148ddd26e7 Merge branch 'MDL-80393-401' of https://github.com/paulholden/moodle into MOODLE_401_STABLE 2023-12-19 17:24:56 +08:00
Paul Holden cdf432ee17 MDL-80393 lang: expose current page language to JS modules.
Since 4be39296 the root HTML element contains the iso6391 language
code of the current language pack. However various JS modules need
access to the original Moodle language pack code, so expose that
in the `M.cfg` structure.
2023-12-19 09:08:12 +00:00
Sara Arjona b1e918edd8 MDL-68124 lesson: Fix random behat error with Oracle
This random error was caused because when reviewing an attempt,
the first pageid to display is calculated based on the timeseen
field in the lesson_attempst table.
In Oracle, sometimes it returned the second pageid (because both
had the same timeseen), so which led to these random failures.

Apart from adding 1-second wait when the attempt is created (to
guarantee the first page is returned properly), a few more
improvements have been also made, like removing manual steps for
setting the lesson activity or adding some extra checks to
confirm the information displayed is expected.
2023-12-18 09:49:05 +01:00
Huong Nguyen f58df6fa88 weekly release 4.1.7+ 2023-12-15 08:44:56 +07:00
Huong Nguyen eae562817d Merge branch 'install_401_STABLE' of https://git.in.moodle.com/amosbot/moodle-install into MOODLE_401_STABLE 2023-12-15 08:44:52 +07:00
Huong Nguyen 033a59f9c5 Merge branch 'MDL-79828-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2023-12-14 10:16:22 +07:00
Huong Nguyen a34a8636be Merge branch 'MDL-79050-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2023-12-14 09:57:28 +07:00
Huong Nguyen 08d2e7c136 Merge branch 'MDL-80394-401' of https://github.com/ilyatregubov/moodle into MOODLE_401_STABLE 2023-12-14 09:23:23 +07:00
Ilya Tregubov 886bbcbdb8 Merge branch 'MDL-79938-m401' of https://github.com/sammarshallou/moodle into MOODLE_401_STABLE 2023-12-14 08:51:51 +08:00
AMOS bot 0c3e759d98 Automatically generated installer lang files 2023-12-14 00:11:04 +00:00
sam marshall 607a452a74 MDL-79938 Behat: Add steps to support multiple tabs 2023-12-13 11:45:51 +00:00
Angelia Dela Cruz 3ef6e04f3c MDL-79050 Behat: Add behat coverage to retake lesson activity 2023-12-13 16:27:02 +08:00
Ilya Tregubov dfc7dcd062 MDL-80394 core_grades: Revert changes to graded_users_iterator
Third party plugins are using it and change was breaking it
2023-12-13 09:38:29 +08:00
Sara Arjona 80d773868c Merge branch 'MDL-80315-401' of https://github.com/andelacruz/moodle into MOODLE_401_STABLE 2023-12-12 14:20:03 +01:00
Sara Arjona eb127cc93b Merge branch 'MDL-79835_401' of https://github.com/timhunt/moodle into MOODLE_401_STABLE 2023-12-12 14:11:51 +01:00
Francis Devine e5eb66e405 MDL-79937 mod_lesson: Fix matching pagetype question matching
The addition of text format on the output of the answer responses broke
the matching later when comparing the valid answer against the sent
response, as the answer response was not correspondingly formatted.

I decided to use the un formatted answer response as the key, to keep it
as close as identical to prior behaviour
2023-12-08 09:06:53 +13:00
Tim Hunt 67f869a081 MDL-79835 behat_core_generator: remove misleading error obfuscation 2023-12-06 18:14:09 +00:00
Angelia Dela Cruz a11a9ca5aa MDL-80315 block_comments: Removed duplicate Behat test
Deleted the duplicated course comments block behat test. The file
blocks/comments/tests/behat/add_comment.feature is deleted as a
result.
2023-12-06 18:26:23 +08:00
David Woloszyn 3fe8dbd027 MDL-80229 core: Add tolerance to min_get_minimum_revision 2023-11-24 15:58:43 +11:00
Angelia Dela Cruz 6aeecbdf46 MDL-79828 core_badges: Delete already awarded course badges 2023-11-21 17:45:47 +08:00
247 changed files with 7685 additions and 3706 deletions
+30 -93
View File
@@ -1,8 +1,12 @@
{
'plugins': [
'babel',
'@babel',
'promise',
'jsdoc',
'jsdoc'
],
'extends': [
'eslint:recommended',
'plugin:promise/recommended'
],
'env': {
'browser': true,
@@ -16,42 +20,19 @@
'M': true,
'Y': true
},
// Warn about unused eslint-disable statements.
'reportUnusedDisableDirectives': true,
'rules': {
// See http://eslint.org/docs/rules/ for all rules and explanations of all
// rules.
// === Possible Errors ===
'comma-dangle': 'off',
'no-compare-neg-zero': 'error',
'no-cond-assign': 'error',
'no-console': 'error',
'no-constant-condition': 'error',
'no-control-regex': 'error',
'no-debugger': 'error',
'no-dupe-args': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-empty': 'warn',
'no-empty-character-class': 'error',
'no-ex-assign': 'error',
'no-extra-boolean-cast': 'error',
'no-extra-parens': 'off',
'no-extra-semi': 'error',
'no-func-assign': 'error',
'no-inner-declarations': 'error',
'no-invalid-regexp': 'error',
'no-irregular-whitespace': 'error',
'no-obj-calls': 'error',
'no-prototype-builtins': 'off',
'no-regex-spaces': 'error',
'no-sparse-arrays': 'error',
'no-unexpected-multiline': 'error',
'no-unreachable': 'warn',
'no-unsafe-finally': 'error',
'no-unsafe-negation': 'error',
'use-isnan': 'error',
'valid-jsdoc': ['warn', { 'requireReturn': false, 'requireParamDescription': false, 'requireReturnDescription': false }],
'valid-typeof': 'error',
// === Best Practices ===
// (these mostly match our jshint config)
@@ -63,15 +44,12 @@
'dot-notation': 'warn',
'no-alert': 'warn',
'no-caller': 'error',
'no-case-declarations': 'error',
'no-div-regex': 'error',
'no-empty-pattern': 'error',
'no-empty-function': 'warn',
'no-eq-null': 'error',
'no-eval': 'error',
'no-extend-native': 'error',
'no-extra-bind': 'warn',
'no-fallthrough': 'error',
'no-floating-decimal': 'warn',
'no-global-assign': 'warn',
'no-implied-eval': 'error',
@@ -83,28 +61,22 @@
'no-multi-str': 'error',
'no-new-func': 'error',
'no-new-wrappers': 'error',
'no-octal': 'error',
'no-octal-escape': 'error',
'no-proto': 'error',
'no-redeclare': 'warn',
'no-restricted-globals': ['error', { 'name': 'Notification' }],
'no-return-assign': 'error',
'no-script-url': 'error',
'no-self-assign': 'error',
'no-self-compare': 'error',
'no-sequences': 'warn',
'no-throw-literal': 'warn',
'no-unmodified-loop-condition': 'error',
'no-unused-expressions': 'error',
'no-unused-labels': 'error',
'no-useless-call': 'warn',
'no-useless-escape': 'warn',
'no-with': 'error',
'wrap-iife': ['error', 'any'],
// === Variables ===
'no-delete-var': 'error',
'no-undef': 'error',
'no-undef-init': 'error',
'no-unused-vars': ['error', { 'caughtErrors': 'none' }],
@@ -137,8 +109,6 @@
'max-statements-per-line': ['warn', { max: 2 }],
'new-cap': ['warn', { 'properties': false }],
'new-parens': 'warn',
'newline-after-var': 'off',
'newline-before-return': 'off',
'newline-per-chained-call': 'off',
'no-array-constructor': 'off',
'no-bitwise': 'error',
@@ -146,7 +116,6 @@
'no-inline-comments': 'off',
'no-lonely-if': 'off',
'no-mixed-operators': 'off',
'no-mixed-spaces-and-tabs': 'error',
'no-multiple-empty-lines': 'warn',
'no-negated-condition': 'off',
'no-nested-ternary': 'warn',
@@ -168,7 +137,6 @@
'padded-blocks': 'off',
'quote-props': ['warn', 'as-needed', {'unnecessary': false, 'keywords': true, 'numbers': true}],
'quotes': 'off',
'require-jsdoc': 'warn',
'semi': 'error',
'semi-spacing': ['warn', {'before': false, 'after': true}],
'sort-vars': 'off',
@@ -181,21 +149,19 @@
'unicode-bom': 'error',
'wrap-regex': 'off',
// === Promises ===
// === Promises (override plugin:promise/recommended) ===
'promise/always-return': 'warn',
'promise/no-return-wrap': 'warn',
'promise/param-names': 'warn',
'promise/catch-or-return': ['warn', {terminationMethod: ['catch', 'fail']}],
'promise/no-native': 'warn',
'promise/no-promise-in-callback': 'warn',
'promise/no-callback-in-promise': 'warn',
'promise/avoid-new': 'warn',
// === Deprecations ===
"no-restricted-properties": ['warn', {
'object': 'M',
'property': 'str',
'message': 'Use AMD module "core/str" or M.util.get_string()'
'message': 'Use "core/str" module or M.util.get_string()'
}],
},
overrides: [
@@ -235,7 +201,6 @@
parser: '@babel/eslint-parser',
// Check AMD with some slightly stricter rules.
rules: {
'no-unused-vars': 'error',
'no-implicit-globals': 'error',
// Disable all of the rules that have babel versions.
'new-cap': 'off',
@@ -247,65 +212,37 @@
'semi': 'off',
'no-unused-expressions': 'off',
// Enable all of the babel version of these rules.
'babel/new-cap': ['warn', { 'properties': false }],
'@babel/new-cap': ['warn', { 'properties': false }],
// Not using this rule for the time being because it isn't
// compatible with jQuery and ES6.
'babel/no-invalid-this': 'off',
'babel/object-curly-spacing': 'warn',
// This is off in the original style int.
'babel/quotes': 'off',
'babel/semi': 'error',
'babel/no-unused-expressions': 'error',
'@babel/no-invalid-this': 'off',
'@babel/object-curly-spacing': 'warn',
'@babel/semi': 'error',
'@babel/no-unused-expressions': 'error',
// === Promises ===
// We have Promise now that we're using ES6.
'promise/no-native': 'off',
'promise/avoid-new': 'off',
// === JSDocs ===
"jsdoc/check-access": [
'error',
],
"jsdoc/check-alignment": 1, // Recommended.
"jsdoc/check-param-names": [
'error',
],
"jsdoc/check-property-names": [
'error',
],
"jsdoc/empty-tags": [
'error',
],
"jsdoc/implements-on-classes": [
'error',
],
"jsdoc/multiline-blocks": [
'error',
],
"jsdoc/require-jsdoc": [
'error',
],
"jsdoc/require-param": [
'error',
],
"jsdoc/require-param-name": [
'error',
],
"jsdoc/require-param-type": [
'error',
],
"jsdoc/require-property": [
'error',
],
"jsdoc/require-property-name": [
'error',
],
"jsdoc/require-property-type": [
'error',
],
'jsdoc/check-access': 'error',
'jsdoc/check-alignment': 1, // Recommended.
'jsdoc/check-param-names': 'error',
'jsdoc/check-property-names': 'error',
'jsdoc/empty-tags': 'error',
'jsdoc/implements-on-classes': 'error',
'jsdoc/multiline-blocks': 'error',
'jsdoc/require-jsdoc': 'error',
'jsdoc/require-param': 'error',
'jsdoc/require-param-name': 'error',
'jsdoc/require-param-type': 'error',
'jsdoc/require-property': 'error',
'jsdoc/require-property-name': 'error',
'jsdoc/require-property-type': 'error'
},
parserOptions: {
'sourceType': 'module',
'requireConfigFile': false,
'requireConfigFile': false
}
}
]
+3 -3
View File
@@ -23,10 +23,10 @@ jobs:
steps:
- name: Checking out code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Configuring node & npm
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
@@ -103,7 +103,7 @@ jobs:
coverage: none
- name: Checking out code from ${{ env.GITHUB_REF_SLUG }}
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Setting up PHPUnit
env:
+3 -3
View File
@@ -16,10 +16,10 @@ jobs:
git config --global core.eol lf
- name: Checking out code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Configuring node & npm
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
@@ -112,7 +112,7 @@ jobs:
git config --global core.eol lf
- name: Checking out code from ${{ env.GITHUB_REF_SLUG }}
uses: actions/checkout@v3
uses: actions/checkout@v4
# Needs to be done after php is available, git configured and Moodle checkout has happened.
- name: Setting up moodle-exttests service
+7 -19
View File
@@ -21,7 +21,7 @@
*/
/**
* Function to generate the destination for the uglify task
* Function to generate the destination for the minification task
* (e.g. build/file.min.js). This function will be passed to
* the rename property of files array when building dynamically:
* http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
@@ -60,7 +60,6 @@ module.exports = grunt => {
grunt.registerTask('js', ['amd', 'yui']);
// Register NPM tasks.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-rollup');
@@ -104,6 +103,7 @@ module.exports = grunt => {
// The queue runner will run the next `size` items in the queue.
const runQueue = (size = 1) => {
queue.splice(0, size).forEach(resolve => {
grunt.log.debug(`Item resolved. Kicking off next one.`);
resolve();
});
};
@@ -113,15 +113,17 @@ module.exports = grunt => {
// The options hook is run in parallel.
// We can return an unresolved Promise which is queued for later resolution.
options: async() => {
options: async(options) => {
return new Promise(resolve => {
queue.push(resolve);
startQueue();
return options;
});
},
// When an item in the queue completes, start the next item in the queue.
buildEnd: () => {
generateBundle: (options, bundle) => {
grunt.log.debug(`Finished output phase for ${Object.keys(bundle).join(', ')}`);
runQueue();
},
};
@@ -151,24 +153,10 @@ module.exports = grunt => {
//
// It also adds the Moodle plugin name to the AMD module definition
// so that it can be imported as expected in other modules.
path.resolve('.grunt/babel-plugin-add-module-to-define.js'),
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-syntax-import-meta',
['@babel/plugin-proposal-class-properties', {'loose': false}],
'@babel/plugin-proposal-json-strings'
path.resolve('.grunt/babel-plugin-add-module-to-define.js')
],
presets: [
['@babel/preset-env', {
targets: {
browsers: [
">0.3%",
"last 2 versions",
"not ie >= 0",
"not op_mini all",
"not Opera > 0",
"not dead"
]
},
modules: false,
useBuiltIns: false
}]
+28 -12
View File
@@ -20,17 +20,33 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
module.exports = grunt => {
// Project configuration.
grunt.config.merge({
jsdoc: {
dist: {
options: {
configure: ".grunt/jsdoc/jsdoc.conf.js",
},
},
},
});
module.exports = (grunt) => {
const path = require('path');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.registerTask('jsdoc', 'Generate JavaScript documentation using jsdoc', function() {
const done = this.async();
const configuration = path.resolve('.grunt/jsdoc/jsdoc.conf.js');
grunt.util.spawn({
cmd: 'jsdoc',
args: [
'--configure',
configuration,
]
}, function(error, result, code) {
if (result.stdout) {
grunt.log.write(result.stdout);
}
if (result.stderr) {
grunt.log.error(result.stderr);
}
if (error) {
grunt.fail.fatal(`JSDoc failed with error code ${code}`);
} else {
grunt.log.write('JSDoc completed successfully'.green);
}
done();
});
});
};
+5 -1
View File
@@ -29,6 +29,7 @@ module.exports = grunt => {
// Use a fully-qualified path.
src: files,
options: {
quietDeprecationWarnings: true,
configOverrides: {
rules: {
// These rules have to be disabled in .stylelintrc for scss compat.
@@ -45,7 +46,10 @@ module.exports = grunt => {
return {
stylelint: {
scss: {
options: {syntax: 'scss'},
options: {
quietDeprecationWarnings: true,
customSyntax: 'postcss-scss',
},
src: files,
},
},
+1 -1
View File
@@ -1 +1 @@
lts/gallium
lts/iron
+16 -4
View File
@@ -1,9 +1,14 @@
{
"customSyntax": "postcss-scss",
"plugins": [
"stylelint-csstree-validator"
],
"rules": {
"csstree/validator": true,
"csstree/validator": {
"syntaxExtensions": [
"sass"
]
},
"at-rule-empty-line-before": [ "always",
{"except": [ "blockless-after-blockless"], ignore: ["after-comment", "inside-block"]}
],
@@ -45,7 +50,7 @@
"function-name-case": "lower",
"function-parentheses-newline-inside": "always-multi-line",
"function-parentheses-space-inside": "never-single-line",
"function-url-scheme-blacklist": ["data"],
"function-url-scheme-disallowed-list": ["data"],
"function-whitespace-after": "always",
"indentation": 4,
"keyframe-declaration-no-important": true,
@@ -84,12 +89,19 @@
"selector-type-no-unknown": true,
"string-no-newline": true,
"time-min-milliseconds": 100,
"unit-blacklist": ["pt"],
"unit-disallowed-list": ["pt"],
"unit-case": "lower",
"unit-no-unknown": true,
"value-keyword-case": ["lower", {"ignoreKeywords": ["/(@|$)/"]}],
"value-list-comma-newline-after": "always-multi-line",
"value-list-comma-space-after": "always-single-line",
"value-list-comma-space-before": "never",
}
},
"overrides": [
{
"files": ["**/yui/**/*.css"],
"rules": {
}
}
]
}
+10
View File
@@ -3923,6 +3923,8 @@
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_xmlrpc_usage" level="optional">
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_oracle_usage" level="optional">
</CUSTOM_CHECK>
</CUSTOM_CHECKS>
</MOODLE>
<MOODLE version="4.2" requires="3.11.8">
@@ -3939,6 +3941,7 @@
<VENDOR name="oracle" version="19" />
</DATABASE>
<PHP version="8.0.0" level="required">
<RESTRICT function="restrict_php_version_83" message="unsupportedphpversion83" />
</PHP>
<PCREUNICODE level="optional">
<FEEDBACK>
@@ -4112,6 +4115,8 @@
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_mod_assignment" level="required">
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_oracle_usage" level="optional">
</CUSTOM_CHECK>
</CUSTOM_CHECKS>
</MOODLE>
<MOODLE version="4.3" requires="3.11.8">
@@ -4128,6 +4133,7 @@
<VENDOR name="oracle" version="19" />
</DATABASE>
<PHP version="8.0.0" level="required">
<RESTRICT function="restrict_php_version_83" message="unsupportedphpversion83" />
</PHP>
<PCREUNICODE level="optional">
<FEEDBACK>
@@ -4303,6 +4309,8 @@
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_db_prefix_length" level="required">
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_oracle_usage" level="optional">
</CUSTOM_CHECK>
</CUSTOM_CHECKS>
</MOODLE>
<MOODLE version="4.4" requires="4.1.2">
@@ -4494,6 +4502,8 @@
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_db_prefix_length" level="required">
</CUSTOM_CHECK>
<CUSTOM_CHECK file="lib/upgradelib.php" function="check_oracle_usage" level="optional">
</CUSTOM_CHECK>
</CUSTOM_CHECKS>
</MOODLE>
</COMPATIBILITY_MATRIX>
@@ -64,7 +64,7 @@ class delete extends base {
* Delete the DB preset
*/
public function execute(): void {
confirm_sesskey();
require_sesskey();
$this->manager->delete_preset($this->id);
@@ -52,8 +52,6 @@ class export extends base {
* Stores a preset into the DB.
*/
public function execute(): void {
confirm_sesskey();
$url = new \moodle_url('/admin/tool/admin_presets/index.php', ['action' => 'export', 'mode' => 'execute']);
$this->moodleform = new export_form($url);
@@ -87,7 +85,7 @@ class export extends base {
* @throws xml_writer_exception
*/
public function download_xml(): void {
confirm_sesskey();
require_sesskey();
list($xmlstr, $filename) = $this->manager->download_preset($this->id);
@@ -40,8 +40,6 @@ class import extends base {
* Imports the xmlfile into DB
*/
public function execute(): void {
confirm_sesskey();
$url = new \moodle_url('/admin/tool/admin_presets/index.php', ['action' => 'import', 'mode' => 'execute']);
$this->moodleform = new import_form($url);
@@ -38,8 +38,6 @@ class load extends base {
public function execute(): void {
global $OUTPUT;
confirm_sesskey();
$url = new \moodle_url('/admin/tool/admin_presets/index.php', ['action' => 'load', 'mode' => 'execute']);
$this->moodleform = new load_form($url);
@@ -73,7 +73,7 @@ class rollback extends base {
public function execute(): void {
global $OUTPUT;
confirm_sesskey();
require_sesskey();
list($presetapp, $rollback, $failures) = $this->manager->revert_preset($this->id);
+7 -7
View File
@@ -97,28 +97,28 @@ if ($onlycli === false) {
switch ($action) {
case 'enable':
confirm_sesskey();
require_sesskey();
$model->enable();
redirect($returnurl);
break;
case 'disable':
confirm_sesskey();
require_sesskey();
$model->update(0, false, false);
redirect($returnurl);
break;
case 'delete':
confirm_sesskey();
require_sesskey();
$model->delete();
redirect($returnurl);
break;
case 'edit':
confirm_sesskey();
require_sesskey();
$invalidcurrenttimesplitting = $model->invalid_timesplitting_selected();
$potentialtimesplittings = $model->get_potential_timesplittings();
@@ -183,7 +183,7 @@ switch ($action) {
break;
case 'evaluate':
confirm_sesskey();
require_sesskey();
if ($model->is_static()) {
throw new moodle_exception('errornostaticevaluate', 'tool_analytics');
@@ -226,7 +226,7 @@ switch ($action) {
break;
case 'scheduledanalysis':
confirm_sesskey();
require_sesskey();
if ($onlycli) {
throw new moodle_exception('erroronlycli', 'tool_analytics');
@@ -292,7 +292,7 @@ switch ($action) {
break;
case 'clear':
confirm_sesskey();
require_sesskey();
$model->clear();
redirect($returnurl);
+34
View File
@@ -0,0 +1,34 @@
@tool_behat
Feature: Confirm that we can open multiple browser tabs
In order to use multiple browser tabs
As a test writer
I need the relevant Behat steps to work
@javascript @_switch_window
Scenario: Open multiple browser tabs
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
| Course 2 | C2 |
| Course 3 | C3 |
And I am on the "C1" "Course" page logged in as "admin"
# Open a new tab on the same page.
When I open a tab named "CourseViewer1" on the current page
And I should see "Course 1" in the "h1" "css_element"
And I am on the "C2" "Course" page
# Open new tab for specified page with identifier.
And I open a tab named "CourseViewer2" on the "C3" "Course" page
# And for a specified page without identifier.
And I open a tab named "CourseViewer4" on the "My courses" page
# Switch between all the tabs and confirm their different contents.
Then I should see "No courses"
And I switch to "CourseViewer2" tab
And "Course 3" "heading" should exist
And I switch to "CourseViewer1" tab
And "Course 2" "heading" should exist
And I switch to the main tab
And "Course 1" "heading" should exist
@@ -120,8 +120,7 @@ Feature: Add customised file types
| Custom description | Froggy file |
And I press "Save changes"
# Create a resource activity and add it to a course
And I am on "Course 1" course homepage with editing mode on
When I add a "File" to section "1"
When I add a resource activity to course "Course 1" section "1"
And I set the following fields to these values:
| Name | An example of customised file type |
| Description | File description |
+1 -1
View File
@@ -114,7 +114,7 @@ if ($mode == DELETION_OF_SELECTED_LANG and (!empty($uninstalllang) or !empty($co
}
}
if ($mode == UPDATE_ALL_LANG) {
if ($mode == UPDATE_ALL_LANG && confirm_sesskey()) {
core_php_time_limit::raise();
$controller->update_all_installed_languages();
}
@@ -87,6 +87,7 @@
<div>
<form id="updateform" action="{{updateurl}}" method="post">
<fieldset>
<input type="hidden" name="sesskey" value="{{sesskey}}">
<input type="submit" value="{{#str}}updatelangs, tool_langimport{{/str}}" class="btn btn-secondary">
{{#hasmanyinstalledlanguages}}
<p class="mt-2 small">{{#str}} updatelangsnote, tool_langimport, {"taskname": {{#quote}}{{updatelangstaskname}}{{/quote}} }{{/str}}</p>
File diff suppressed because one or more lines are too long
-2
View File
@@ -71,14 +71,12 @@ define(['jquery'], function($) {
return null;
};
// eslint-disable-line valid-jsdoc
/**
* Return the type of the module.
*
* @return {String}
* @method getType
*/
// eslint-enable-line valid-jsdoc
Rule.prototype.getType = function() {
throw new Error('Not implemented');
};
@@ -0,0 +1,45 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace tool_mobile;
use core\session\utility\cookie_helper;
use core\event\user_loggedin;
/**
* Event handler for tool_mobile.
*
* @package tool_mobile
* @copyright 2024 Juan Leyva
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class event_handler {
/**
* Allows the plugin to augment Set-Cookie headers when the user_loggedin event is fired as part of complete_user_login() calls.
*
* @param user_loggedin $event the event
* @return void
*/
public static function handle_user_loggedin(user_loggedin $event): void {
global $CFG;
// Set Partitioned and Secure attributes to the MoodleSession cookie if the user is using the Moodle app.
if (\core_useragent::is_moodle_app()) {
cookie_helper::add_attributes_to_cookie_response_header('MoodleSession'.$CFG->sessioncookie, ['Secure', 'Partitioned']);
}
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* tool_mobile plugin event handler definition.
*
* @package tool_mobile
* @category event
* @copyright 2024 Juan Leyva
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$observers = [
[
'eventname' => '\core\event\user_loggedin',
'callback' => '\tool_mobile\event_handler::handle_user_loggedin',
],
];
+13
View File
@@ -265,3 +265,16 @@ function tool_mobile_pre_processor_message_send($procname, $data) {
$data->fullmessagehtml .= html_writer::tag('p', get_string('readingthisemailgettheapp', 'tool_mobile', $url->out()));
}
}
/**
* Callback to add headers before the HTTP headers are sent.
*
*/
function tool_mobile_before_http_headers() {
global $CFG;
// Set Partitioned and Secure attributes to the MoodleSession cookie if the user is using the Moodle app.
if (\core_useragent::is_moodle_app()) {
\core\session\utility\cookie_helper::add_attributes_to_cookie_response_header('MoodleSession'.$CFG->sessioncookie, ['Secure', 'Partitioned']);
}
}
+1 -1
View File
@@ -23,7 +23,7 @@
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2022112800; // The current plugin version (Date: YYYYMMDDXX).
$plugin->version = 2022112801; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2022111800; // Requires this Moodle version.
$plugin->component = 'tool_mobile'; // Full name of the plugin (used for diagnostics).
$plugin->dependencies = array(
File diff suppressed because one or more lines are too long
@@ -121,7 +121,6 @@ define(['tool_moodlenet/validator',
});
// Trigger the transition between 'pages'.
carousel.carousel(2);
// eslint-disable-next-line max-len
modal.setFooter(Templates.render('tool_moodlenet/chooser_footer_close_mnet', {}));
};
+6 -7
View File
@@ -50,12 +50,10 @@ list($options, $unrecognized) = cli_get_params(
)
);
if (file_exists(__DIR__.'/../../../../vendor/phpunit/phpunit/composer.json')) {
// Composer packages present.
require_once(__DIR__.'/../../../../vendor/autoload.php');
} else {
// Note: installation via PEAR is not supported any more.
// Basic check to see if phpunit is installed.
if (!file_exists(__DIR__.'/../../../../vendor/phpunit/phpunit/composer.json') ||
!file_exists(__DIR__.'/../../../../vendor/bin/phpunit') ||
!file_exists(__DIR__.'/../../../../vendor/autoload.php')) {
phpunit_bootstrap_error(PHPUNIT_EXITCODE_PHPUNITMISSING);
}
@@ -74,12 +72,13 @@ if ($options['run']) {
}
}
$_SERVER['argv'] = array_values($_SERVER['argv']);
PHPUnit\TextUI\Command::main();
require(__DIR__ . '/../../../../vendor/bin/phpunit');
exit(0);
}
define('PHPUNIT_UTIL', true);
require(__DIR__.'/../../../../vendor/autoload.php');
require(__DIR__ . '/../../../../lib/phpunit/bootstrap.php');
// from now on this is a regular moodle CLI_SCRIPT
+2 -1
View File
@@ -87,7 +87,8 @@ require_sesskey();
// Prepare to handle output via mtrace.
echo html_writer::start_tag('pre');
require('lib.php');
require_once("{$CFG->dirroot}/{$CFG->admin}/tool/task/lib.php");
$CFG->mtrace_wrapper = 'tool_task_mtrace_wrapper';
// Run the specified task (this will output an error if it doesn't exist).
+1 -1
View File
@@ -116,7 +116,7 @@ class auth_plugin_lti extends \auth_plugin_base {
if (isloggedin()) {
// If a different user is currently logged in, authenticate the linked user instead.
global $USER;
if ((int) $USER->id !== $user->id) {
if ($USER->id !== $user->id) {
complete_user_login($user);
}
// If the linked user is already logged in, skip the call to complete_user_login() because this affects deep linking
@@ -0,0 +1,48 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace auth_lti\local\ltiadvantage\event;
use auth_lti\local\ltiadvantage\utility\cookie_helper;
use core\event\user_loggedin;
/**
* Event handler for auth_lti.
*
* @package auth_lti
* @copyright 2024 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class event_handler {
/**
* Allows the plugin to augment Set-Cookie headers when the user_loggedin event is fired as part of complete_user_login() calls.
*
* @param user_loggedin $event the event
* @return void
*/
public static function handle_user_loggedin(user_loggedin $event): void {
// The event data isn't important here. The intent of this listener is to ensure that the MoodleSession cookie is set up
// properly during LTI launches + login. This means two things:
// i) it's set with SameSite=None; Secure; where possible (since OIDC needs HTTPS this will almost always be possible).
// ii) it set with the 'Partitioned' attribute, when required.
// The former ensures cross-site cookies are sent for embedded launches. The latter is an opt-in flag needed to use Chrome's
// partitioning mechanism, CHIPS.
if (cookie_helper::cookies_supported()) {
cookie_helper::setup_session_cookie();
}
}
}
@@ -0,0 +1,173 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace auth_lti\local\ltiadvantage\utility;
use core\session\utility\cookie_helper as core_cookie_helper;
/**
* Helper class providing utils dealing with cookies in LTI, particularly 3rd party cookies.
*
* @package auth_lti
* @copyright 2024 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class cookie_helper {
/** @var int Cookies are not supported. */
public const COOKIE_METHOD_NOT_SUPPORTED = 0;
/** @var int Cookies are supported without explicit partitioning. */
public const COOKIE_METHOD_NO_PARTITIONING = 1;
/** @var int Cookies are supported via explicit partitioning. */
public const COOKIE_METHOD_EXPLICIT_PARTITIONING = 2;
/**
* Check whether cookies can be used with the current user agent and, if so, via what method they are set.
*
* Currently, this tries 2 modes of setting a test cookie:
* 1. Setting a SameSite=None, Secure cookie. This will work in any first party context, and in 3rd party contexts for
* any browsers supporting automatic partitioning of 3rd party cookies (E.g. Firefox, Brave).
* 2. If 1 fails, setting a cookie with the Chrome 'Partitioned' attribute included, opting that cookie into CHIPS. This will
* work for Chrome.
*
* Upon completion of the cookie check, the check sets a SESSION flag indicating the method used to set the cookie, and upgrades
* the session cookie ('MoodleSession') using the respective method. This ensure the session cookie will continue to be sent.
*
* Then, the following methods can be used by client code to query whether the UA supports cookies, and how:
* @see self::cookies_supported() - whether it could be set at all.
* @see self::get_cookies_supported_mode() - if a cookie could be set, what mode was used to set it.
*
* This permits client code to make sure it's setting its cookies appropriately (via the advertised method), and allows it to
* present notices - such as in the case where a given UA is found to be lacking the requisite cookie support.
* E.g.
* cookie_helper::do_cookie_check($mypageurl);
* if (!cookie_helper::cookies_supported()) {
* // Print a notice stating that cookie support is required.
* }
* // Elsewhere in other client code...
* if (cookie_helper::get_cookies_supported_mode() === cookie_helper::COOKIE_METHOD_EXPLICIT_PARTITIONING) {
* // Set a cookie, making sure to use the helper to also opt-in to partitioning.
* setcookie('myauthcookie', 'myauthcookievalue', ['samesite' => 'None', 'secure' => true]);
* cookie_helper::add_partitioning_to_cookie('myauthcookie');
* }
*
* @param \moodle_url $pageurl the URL of the page making the check, used to redirect back to after setting test cookies.
* @return void
*/
public static function do_cookie_check(\moodle_url $pageurl): void {
global $_COOKIE, $SESSION, $CFG;
$cookiecheck1 = optional_param('cookiecheck1', null, PARAM_INT);
$cookiecheck2 = optional_param('cookiecheck2', null, PARAM_INT);
if (empty($cookiecheck1)) {
// Start the cookie check. Set two test cookies - one samesite none, and one partitioned - and redirect.
// Set cookiecheck to show the check has started.
self::set_test_cookie('cookiecheck1', self::COOKIE_METHOD_NO_PARTITIONING);
self::set_test_cookie('cookiecheck2', self::COOKIE_METHOD_EXPLICIT_PARTITIONING, true);
$pageurl->params([
'cookiecheck1' => self::COOKIE_METHOD_NO_PARTITIONING,
'cookiecheck2' => self::COOKIE_METHOD_EXPLICIT_PARTITIONING,
]);
// LTI needs to guarantee the 'SameSite=None', 'Secure' (and sometimes 'Partitioned') attributes are set on the
// MoodleSession cookie. This is done via manipulation of the outgoing headers after the cookie check redirect. To
// guarantee these outgoing Set-Cookie headers will be created after the redirect, expire the current cookie.
core_cookie_helper::expire_moodlesession();
redirect($pageurl);
} else {
// Have already started a cookie check, so check the result.
$cookie1received = isset($_COOKIE['cookiecheck1']) && $_COOKIE['cookiecheck1'] == $cookiecheck1;
$cookie2received = isset($_COOKIE['cookiecheck2']) && $_COOKIE['cookiecheck2'] == $cookiecheck2;
if ($cookie1received || $cookie2received) {
// The test cookie could be set and received.
// Set a session flag storing the method used to set it, and make sure the session cookie uses this method.
$cookiemethod = $cookie1received ? self::COOKIE_METHOD_NO_PARTITIONING : self::COOKIE_METHOD_EXPLICIT_PARTITIONING;
$SESSION->auth_lti_cookie_method = $cookiemethod;
self::setup_session_cookie();
}
}
}
/**
* If a cookie check has been made, returns whether cookies could be set or not.
*
* @return bool whether cookies are supported or not.
*/
public static function cookies_supported(): bool {
return self::get_cookies_supported_method() !== self::COOKIE_METHOD_NOT_SUPPORTED;
}
/**
* If a cookie check has been made, gets the method used to set a cookie, or self::COOKIE_METHOD_NOT_SUPPORTED if not supported.
*
* For cookie methods:
* @see self::COOKIE_METHOD_NOT_SUPPORTED
* @see self::COOKIE_METHOD_NO_PARTITIONING
* @see self::COOKIE_METHOD_EXPLICIT_PARTITIONING
*
* @return int the constant representing the method by which the cookie was set, or not.
*/
public static function get_cookies_supported_method(): int {
global $SESSION;
return $SESSION->auth_lti_cookie_method ?? self::COOKIE_METHOD_NOT_SUPPORTED;
}
/**
* Sets up the session cookie according to the method used in the cookie check, and with SameSite=None; Secure attributes.
*
* @return void
*/
public static function setup_session_cookie(): void {
global $CFG;
require_once($CFG->libdir . '/sessionlib.php');
if (is_moodle_cookie_secure()) {
$atts = ['SameSite=None', 'Secure'];
if (self::get_cookies_supported_method() == self::COOKIE_METHOD_EXPLICIT_PARTITIONING) {
$atts[] = 'Partitioned';
}
core_cookie_helper::add_attributes_to_cookie_response_header('MoodleSession' . $CFG->sessioncookie, $atts);
}
}
/**
* Set a test cookie, using SameSite=None; Secure; attributes if possible, and with or without partitioning opt-in.
*
* @param string $name cookie name
* @param string $value cookie value
* @param bool $partitioned whether to try to add partitioning opt-in, which requires secure cookies (https sites).
* @return void
*/
private static function set_test_cookie(string $name, string $value, bool $partitioned = false): void {
global $CFG;
require_once($CFG->libdir . '/sessionlib.php');
$atts = ['expires' => time() + 30];
if (is_moodle_cookie_secure()) {
$atts['samesite'] = 'none';
$atts['secure'] = true;
}
setcookie($name, $value, $atts);
if (is_moodle_cookie_secure() && $partitioned) {
core_cookie_helper::add_attributes_to_cookie_response_header($name, ['Partitioned']);
}
}
}
+5 -6
View File
@@ -33,33 +33,32 @@ class renderer extends \plugin_renderer_base {
* @return string the html.
*/
public function render_account_binding_options_page(int $provisioningmode): string {
$formaction = new \moodle_url('/auth/lti/login.php');
$notification = new notification(get_string('firstlaunchnotice', 'auth_lti'), \core\notification::INFO, false);
$noauthnotice = new notification(get_string('firstlaunchnoauthnotice', 'auth_lti', get_docs_url('Publish_as_LTI_tool')),
\core\notification::WARNING, false);
$cancreateaccounts = !get_config('moodle', 'authpreventaccountcreation');
if ($provisioningmode == \auth_plugin_lti::PROVISIONING_MODE_PROMPT_EXISTING_ONLY) {
$cancreateaccounts = false;
}
$accountinfo = ['isloggedin' => isloggedin()];
$accountinfo = [];
if (isloggedin()) {
global $USER;
$accountinfo = array_merge($accountinfo, [
$accountinfo = [
'firstname' => $USER->firstname,
'lastname' => $USER->lastname,
'email' => $USER->email,
'picturehtml' => $this->output->user_picture($USER, ['size' => 35, 'class' => 'round']),
]);
];
}
$context = [
'isloggedin' => isloggedin(),
'info' => $notification->export_for_template($this),
'formaction' => $formaction->out(),
'sesskey' => sesskey(),
'accountinfo' => $accountinfo,
'cancreateaccounts' => $cancreateaccounts,
'noauthnotice' => $noauthnotice->export_for_template($this)
];
return parent::render_from_template('auth_lti/local/ltiadvantage/login', $context);
}
+33
View File
@@ -0,0 +1,33 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* LTI Auth plugin event handler definition.
*
* @package auth_lti
* @category event
* @copyright 2024 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$observers = [
[
'eventname' => '\core\event\user_loggedin',
'callback' => '\auth_lti\local\ltiadvantage\event\event_handler::handle_user_loggedin',
],
];
+1 -1
View File
@@ -35,7 +35,7 @@ $string['firstlaunchnoauthnotice'] = 'To link your existing account you must be
$string['getstartedwithnewaccount'] = 'Get started with a new account';
$string['haveexistingaccount'] = 'I have an existing account';
$string['linkthisaccount'] = 'Link this account';
$string['mustbeloggedin'] = 'You need to be logged in to your existing account';
$string['mustbeloggedin'] = 'Sign in to link your existing account';
$string['pluginname'] = 'LTI';
$string['privacy:metadata:auth_lti'] = 'LTI authentication';
$string['privacy:metadata:auth_lti:authsubsystem'] = 'This plugin is connected to the authentication subsystem.';
@@ -32,7 +32,6 @@
* info - a notification describing the first launch options
* cancreateaccounts - whether or not the user is allowed to create auth_lti accounts
* accountinfo - information about the user, importantly whether they are logged in or not.
* noauthnotice - a notification telling the user they must be authenticated to link accounts. Only relevant when not logged in.
Example context (json):
{
@@ -46,19 +45,12 @@
"issuccess": true
},
"cancreateaccounts": true,
"isloggedin": true,
"accountinfo": {
"isloggedin": true,
"firstname": "John",
"lastname": "Smith",
"email": "john@example.com",
"picturehtml": "<img src=\"http://site.example.com/pluginfile.php/5/user/icon/boost/f2?rev=99\" class=\"round\" alt=\"\" width=\"35\" height=\"35\">"
},
"noauthnotice": {
"message": "To link your existing account you must be logged in to the site...",
"extraclasses": "",
"announce": false,
"closebutton": false,
"iswarning": true
}
}
}}
@@ -79,8 +71,8 @@
<div class="card-body text-center d-flex flex-column">
<i class="fa fa-user-circle-o fa-2x link"></i>
<h4 class="card-title">{{#str}} useexistingaccount, auth_lti {{/str}}</h4>
{{#accountinfo}}
{{#isloggedin}}
{{#accountinfo}}
<p class="card-text mt-2">
<span class="text-muted">
{{#str}} currentlyloggedinas, auth_lti {{/str}}
@@ -90,14 +82,12 @@
{{firstname}} {{lastname}} ({{email}})
</p>
<input type="submit" class="btn btn-primary mt-auto" name="existing_account" value="{{#str}} linkthisaccount, auth_lti {{/str}}">
{{/accountinfo}}
{{/isloggedin}}
{{^isloggedin}}
<p class="card-text text-muted">{{#str}} mustbeloggedin, auth_lti {{/str}}</p>
{{#noauthnotice}}
{{> core/notification}}
{{/noauthnotice}}
<input type="submit" class="btn btn-primary mt-auto" name="existing_account" value="{{#str}} login, moodle {{/str}}">
{{/isloggedin}}
{{/accountinfo}}
</div>
</div>
</div>
+1 -1
View File
@@ -24,6 +24,6 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2022112800; // The current plugin version (Date: YYYYMMDDXX).
$plugin->version = 2022112801; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2022111800; // Requires this Moodle version.
$plugin->component = 'auth_lti'; // Full name of the plugin (used for diagnostics).
@@ -119,3 +119,97 @@ Feature: Award badges with separate groups
And I press "Award badge"
# Teacher 2 shouldn't be able to go further
Then I should see "Sorry, but you need to be part of a group to see this page."
@javascript
Scenario: Editing teacher can award badge to members of separate groups
Given I am on the "Course 1" course page logged in as teacher1
And I navigate to "Badges > Manage badges" in current page administration
And I follow "Course Badge"
And I press "Award badge"
When I set the field "role" to "Teacher"
# Confirm that editing teacher sees a separate groups dropdown menu.
Then "Separate groups" "select" should exist
And I should see "All participants" in the "Separate groups" "select"
# Confirm that all participants are displayed when All participants is selected.
And I should see "Student 1" in the "potentialrecipients[]" "select"
And I should see "Student 2" in the "potentialrecipients[]" "select"
And I should see "Teacher 1" in the "potentialrecipients[]" "select"
And I should see "Teacher 2" in the "potentialrecipients[]" "select"
And I set the field "Separate groups" to "Class A"
# Confirm that only members of selected group are displayed
And I should not see "Student 1" in the "potentialrecipients[]" "select"
And I should not see "Teacher 1" in the "potentialrecipients[]" "select"
And I should see "Student 2" in the "potentialrecipients[]" "select"
And I should see "Teacher 2" in the "potentialrecipients[]" "select"
And I set the field "Separate groups" to "Class B"
And I should not see "Student 2" in the "potentialrecipients[]" "select"
And I should not see "Teacher 2" in the "potentialrecipients[]" "select"
And I should see "Student 1" in the "potentialrecipients[]" "select"
And I should see "Teacher 1" in the "potentialrecipients[]" "select"
@javascript
Scenario Outline: Teacher can award badge to members of visible groups
Given I am on the "Course 1" "course editing" page logged in as teacher1
And I expand all fieldsets
# Set the group mode to visible groups.
And I set the field "Group mode" to "Visible groups"
And I press "Save and display"
When I am on the "Course 1" course page logged in as <loggedinuser>
And I navigate to "Badges > Manage badges" in current page administration
And I follow "Course Badge"
And I press "Award badge"
And I set the field "role" to "<awarder>"
# Confirm that teachers see a visible groups dropdown menu.
Then "Visible groups" "select" should exist
# Confirm that My groups option group exists.
And "optgroup[label='My groups']" "css_element" should exist in the "select[name='group']" "css_element"
# Confirm that Other groups option group exists.
And "optgroup[label='Other groups']" "css_element" should exist in the "select[name='group']" "css_element"
# Confirm that all participants are displayed when All participants is selected.
And I set the field "Visible groups" to "All participants"
And I should see "Student 1" in the "potentialrecipients[]" "select"
And I should see "Student 2" in the "potentialrecipients[]" "select"
And I should see "Teacher 1" in the "potentialrecipients[]" "select"
And I should see "Teacher 2" in the "potentialrecipients[]" "select"
# Confirm that only members of selected group are displayed.
And I set the field "Visible groups" to "Class A"
And I should not see "Student 1" in the "potentialrecipients[]" "select"
And I should not see "Teacher 1" in the "potentialrecipients[]" "select"
And I should see "Student 2" in the "potentialrecipients[]" "select"
And I should see "Teacher 2" in the "potentialrecipients[]" "select"
And I set the field "Visible groups" to "Class B"
And I should not see "Student 2" in the "potentialrecipients[]" "select"
And I should not see "Teacher 2" in the "potentialrecipients[]" "select"
And I should see "Student 1" in the "potentialrecipients[]" "select"
And I should see "Teacher 1" in the "potentialrecipients[]" "select"
Examples:
| loggedinuser | awarder |
| teacher1 | Teacher |
| teacher2 | Non-editing teacher |
@javascript
Scenario Outline: Teacher can award badge to members when group mode is set to no groups
Given I am on the "Course 1" "course editing" page logged in as teacher1
And I expand all fieldsets
# Set the group mode to no groups.
And I set the field "Group mode" to "No groups"
And I press "Save and display"
When I am on the "Course 1" course page logged in as <loggedinuser>
And I navigate to "Badges > Manage badges" in current page administration
And I follow "Course Badge"
And I press "Award badge"
And I set the field "role" to "<awarder>"
# Confirm that no group dropdowns don't exist.
Then "Separate groups" "select" should not exist
And "Visible groups" "select" should not exist
# Confirm all participants are displayed.
And I should see "Student 1" in the "potentialrecipients[]" "select"
And I should see "Student 2" in the "potentialrecipients[]" "select"
And I should see "Teacher 1" in the "potentialrecipients[]" "select"
And I should see "Teacher 2" in the "potentialrecipients[]" "select"
Examples:
| loggedinuser | awarder |
| teacher1 | Teacher |
| teacher2 | Non-editing teacher |
@@ -0,0 +1,52 @@
@core @core_badges
Feature: Delete course badge already awarded
As a teacher
I can delete awarded course badge
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | 1 | teacher1@example.com |
| student1 | Student | 1 | student1@example.com |
And the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
@javascript
Scenario Outline: Delete course badge already awarded to student
Given the following "core_badges > Badges" exist:
| name | course | description | image | status | type |
| <badgename> | C1 | <badgename> description | badges/tests/behat/badge.png | active | 2 |
And the following "core_badges > Criterias" exist:
| badge | role |
| <badgename> | editingteacher |
And the following "core_badges > Issued badges" exist:
| badge | user |
| <badgename> | student1 |
When I am on the "Course 1" "enrolled users" page logged in as "teacher1"
And I click on "Student 1" "link"
Then I should see "<badgename>"
And I am on the "Course 1" course page
# Navigate to Manage Badges page in order to delete the badge
And I navigate to "Badges > Manage badges" in current page administration
# Delete the badge
And I click on "Delete" "icon" in the "<badgename>" "table_row"
And I press "<deleteoption>"
And I am on the "Course 1" "enrolled users" page
And I click on "Student 1" "link"
# Confirm that Badge 1 is retained as awarded badge but Badge 2 is not
And I <visibility> see "<badgename>"
And I am on the "Course 1" course page
# Navigate to Badges page to confirm that no badges exist, hence, Manage badges would not exist
And I navigate to "Badges" in current page administration
# Confirm that badges are sucessfully deleted
And I should see "There are currently no badges available for users to earn."
Examples:
| badgename | deleteoption | visibility |
| Badge 1 | Delete and keep existing issued badges | should |
| Badge 2 | Delete and remove existing issued badges | should not |
+20 -1
View File
@@ -59,7 +59,26 @@ function block_comments_comment_validate($comment_param) {
* @return array
*/
function block_comments_comment_permissions($args) {
return array('post'=>true, 'view'=>true);
global $DB, $USER;
// By default, anyone can post and view comments.
$canpost = $canview = true;
// Check if it's the user context and not the owner's profile.
if ($args->context->contextlevel == CONTEXT_USER && $USER->id != $args->context->instanceid) {
// Check whether the context owner has a comment block in the user's profile.
$sqlparam = [
'blockname' => 'comments',
'parentcontextid' => $args->context->id,
'pagetypepattern' => 'user-profile',
];
// If the comment block is not present at the target user's profile,
// then the logged-in user cannot post or view comments.
$canpost = $canview = $DB->record_exists_select(
'block_instances',
'blockname = :blockname AND parentcontextid = :parentcontextid AND pagetypepattern = :pagetypepattern',
$sqlparam,
);
}
return ['post' => $canpost, 'view' => $canview];
}
/**
@@ -10,7 +10,7 @@ Feature: Add a comment to the comments block
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -25,11 +25,16 @@ Feature: Add a comment to the comments block
Scenario: Add a comment with Javascript enabled
When I add "I'm a comment from student1" comment to comments block
Then I should see "I'm a comment from student1"
And I am on the "Course 1" course page logged in as teacher1
And I should see "I'm a comment from student1"
Scenario: Add a comment with Javascript disabled
When I follow "Show comments"
And I add "I'm a comment from student1" comment to comments block
Then I should see "I'm a comment from student1"
And I am on the "Course 1" course page logged in as teacher1
And I follow "Show comments"
And I should see "I'm a comment from student1"
@javascript
Scenario: Test comment block pagination
@@ -10,7 +10,7 @@ Feature: Enable Block comments on an activity page and view comments
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -1,27 +0,0 @@
@block @block_comments
Feature: Enable Block comments on a course page and view comments
In order to enable the comments block on a course page
As a teacher
I can add the comments block to the course page
Scenario: Add the comments block on the course page and add comments
Given the following "courses" exist:
| fullname | shortname | category |
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "blocks" exist:
| blockname | contextlevel | reference | pagetypepattern | defaultregion |
| comments | Course | C1 | course-view-* | side-pre |
And I am on the "Course 1" course page logged in as teacher1
And I follow "Show comments"
And I add "I'm a comment from the teacher" comment to comments block
When I am on the "Course 1" course page logged in as student1
And I follow "Show comments"
Then I should see "I'm a comment from the teacher"
@@ -10,7 +10,7 @@ Feature: Enable Block comments on the dashboard and view comments
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
Scenario: Add the comments block on the dashboard and add comments with Javascript disabled
When I log in as "teacher1"
+12 -10
View File
@@ -101,13 +101,14 @@ class block_tag_flickr extends block_base {
$request .= '&api_key='.FLICKR_DEV_KEY;
$request .= '&photoset_id='.$this->config->photoset;
$request .= '&per_page='.$numberofphotos;
$request .= '&format=php_serial';
$request .= '&format=json';
// We need to add nojsoncallback=? here, otherwise, Flickr will return the jsonFlickrApi object.
$request .= '&nojsoncallback=?';
$response = $this->fetch_request($request);
$search = @unserialize($response);
if ($search === false && $search != serialize(false)) {
// The response didn't appear to be anything serialized, exit...
$search = @json_decode($response, true);
if (!is_array($search) || json_last_error() !== JSON_ERROR_NONE) {
// The response didn't appear to be in correct format.
return;
}
@@ -126,13 +127,14 @@ class block_tag_flickr extends block_base {
$request .= '&tags='.$tagscsv;
$request .= '&per_page='.$numberofphotos;
$request .= '&sort='.$sortby;
$request .= '&format=php_serial';
$request .= '&format=json';
// We need to add nojsoncallback=? here, otherwise, Flickr will return the jsonFlickrApi object.
$request .= '&nojsoncallback=?';
$response = $this->fetch_request($request);
$search = @unserialize($response);
if ($search === false && $search != serialize(false)) {
// The response didn't appear to be anything serialized, exit...
$search = @json_decode($response, true);
if (!is_array($search) || json_last_error() !== JSON_ERROR_NONE) {
// The response didn't appear to be in correct format.
return;
}
$photos = array_values($search['photos']['photo']);
+2 -1
View File
@@ -608,7 +608,8 @@ class cache implements cache_loader {
// store; parent method will have set it to all stores if needed.
if ($setaftervalidation) {
$lock = null;
if (!empty($this->requirelockingbeforewrite)) {
// Only try to acquire a lock for this cache if we do not already have one.
if (!empty($this->requirelockingbeforewrite) && !$this->check_lock_state($key)) {
$lock = $this->acquire_lock($key);
}
if ($requiredversion === self::VERSION_NONE) {
@@ -78,7 +78,8 @@ trait eventtype {
if (!empty($eventtypes['user']) && count($options) == 1) {
$mform->addElement('hidden', 'eventtype');
$mform->setType('eventtype', PARAM_TEXT);
$mform->setDefault('eventtype', 'user');
$mform->hardFreeze('eventtype');
$mform->setConstant('eventtype', 'user');
return;
} else {
$mform->addElement('select', 'eventtype', get_string('eventkind', 'calendar'), $options);
@@ -106,7 +106,7 @@ class managesubscriptions extends \moodleform {
$courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
$eventtypes = calendar_get_allowed_event_types($courseid);
if (empty($eventtype) || !isset($eventtypes[$eventtype])) {
if (empty($eventtype) || !isset($eventtypes[$eventtype]) || $eventtypes[$eventtype] == false) {
$errors['eventtype'] = get_string('invalideventtype', 'calendar');
}
+11 -1
View File
@@ -898,7 +898,17 @@ class core_calendar_external extends external_api {
$courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
$editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
$formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
$formoptions['eventtypes'] = calendar_get_allowed_event_types($courseid);
$allowedeeventtypes = calendar_get_allowed_event_types($courseid);
// Event type validation.
if (in_array(true, $allowedeeventtypes, true) === false) {
throw new \moodle_exception('nopermissiontoupdatecalendar');
}
if (empty($eventtype) || !isset($allowedeeventtypes[$eventtype]) || $allowedeeventtypes[$eventtype] == false) {
return ['validationerror' => true];
}
$formoptions['eventtypes'] = $allowedeeventtypes;
if ($courseid) {
require_once($CFG->libdir . '/grouplib.php');
$groupcoursedata = groups_get_course_data($courseid);
+17 -1
View File
@@ -176,7 +176,23 @@ class behat_calendar extends behat_base {
* @return void
*/
public function i_am_viewing_site_calendar() {
$url = new moodle_url('/calendar/view.php', ['view' => 'month']);
$this->i_am_viewing_calendar_in_view('month');
}
/**
* Navigate to a specific view in the calendar.
*
* @Given /^I am viewing calendar in "([^"]+)" view$/
* @param string $view The calendar view ('month', 'day' and 'upcoming') to navigate to.
* @return void
*/
public function i_am_viewing_calendar_in_view(string $view): void {
if (!in_array($view, ['month', 'day', 'upcoming'])) {
throw new Exception("Invalid calendar view. Allowed values are: 'month', 'day' and 'upcoming'");
}
$url = new moodle_url('/calendar/view.php', ['view' => $view]);
$this->execute('behat_general::i_visit', [$url]);
}
}
@@ -5,8 +5,8 @@ Feature: Allow to mark course as completed without cron for activity completion
Background:
Given the following "courses" exist:
| fullname | shortname | category |
| Completion course | CC1 | 0 |
| fullname | shortname | category | enablecompletion |
| Completion course | CC1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | First | student1@example.com |
@@ -25,11 +25,7 @@ Feature: Allow to mark course as completed without cron for activity completion
And the following "blocks" exist:
| blockname | contextlevel | reference | pagetypepattern | defaultregion |
| completionstatus | Course | CC1 | course-view-* | side-pre |
And I am on the "Completion course" "course editing" page logged in as admin
And I expand all fieldsets
And I set the field "Enable completion tracking" to "Yes"
And I click on "Save and display" "button"
And I am on the "Test assignment name" "assign activity editing" page
And I am on the "Test assignment name" "assign activity editing" page logged in as admin
And I follow "Expand all"
And I set the field "Completion tracking" to "Show activity as complete when conditions are met"
And I set the field "completionusegrade" to "1"
@@ -10,7 +10,7 @@ Feature: Allow teachers to bulk edit activity completion rules in a course.
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -6,8 +6,8 @@ Feature: Show activity completion status or activity completion configuration on
Background:
Given the following "courses" exist:
| fullname | shortname | category |
| Course 1 | C1 | 0 |
| fullname | shortname | category | enablecompletion |
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | First | teacher1@example.com |
@@ -18,12 +18,6 @@ Feature: Show activity completion status or activity completion configuration on
| teacher1 | C1 | editingteacher |
| teacher2 | C1 | teacher |
| student1 | C1 | student |
And I log in as "teacher1"
And I am on "Course 1" course homepage with editing mode on
And I navigate to "Settings" in current page administration
And I set the following fields to these values:
| Enable completion tracking | Yes |
And I press "Save and display"
And the following "activities" exist:
| activity | course | idnumber | name | intro | completion | completionview | completionexpected |
| assign | C1 | assign1 | Test assignment name | Test assignment description | 2 | 1 | 0 |
@@ -14,7 +14,7 @@ Feature: Allow teachers to edit the default activity completion rules in a cours
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -56,7 +56,7 @@ Feature: Allow teachers to edit the default activity completion rules in a cours
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
@@ -7,7 +7,7 @@ Feature: Students will be marked as completed if they have achieved a passing gr
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
| student2 | Student | Second | student2@example.com |
And the following "course enrolments" exist:
@@ -8,7 +8,7 @@ Feature: Students will be marked as completed and pass/fail
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
| student2 | Student | Second | student2@example.com |
| student3 | Student | Third | student3@example.com |
@@ -7,29 +7,22 @@ Feature: Allow students to manually mark an activity as complete
@javascript
Scenario: Mark an activity as completed
Given the following "courses" exist:
| fullname | shortname | category |
| Course 1 | C1 | 0 |
| fullname | shortname | category | enablecompletion |
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activity" exists:
| activity | forum |
| course | C1 |
| name | Test forum name |
| activity | forum |
| course | C1 |
| name | Test forum name |
| completion | 1 |
And I am on the "Course 1" course page logged in as teacher1
And I navigate to "Settings" in current page administration
And I set the following fields to these values:
| Enable completion tracking | Yes |
And I press "Save and display"
And I am on the "Test forum name" "forum activity editing" page
And I set the following fields to these values:
| completion | 1 |
And I press "Save and return to course"
And "Student First" user has not completed "Test forum name" activity
And I am on the "Course 1" course page logged in as student1
When I toggle the manual completion state of "Test forum name"
@@ -10,7 +10,7 @@ Feature: Students will be shown relevant completion state based on grade item vi
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
| student2 | Student | Second | student2@example.com |
And the following "course enrolments" exist:
@@ -10,7 +10,7 @@ Feature: Restrict activity availability through date conditions
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -11,7 +11,7 @@ Feature: Restrict activity availability through grade conditions
| Course 1 | C1 | 0 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -6,11 +6,11 @@ Feature: Restrict sections availability through completion or grade conditions
Background:
Given the following "courses" exist:
| fullname | shortname | category |
| Course 1 | C1 | 0 |
| fullname | shortname | category | enablecompletion |
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Frist | teacher1@example.com |
| teacher1 | Teacher | First | teacher1@example.com |
| student1 | Student | First | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
@@ -23,15 +23,11 @@ Feature: Restrict sections availability through completion or grade conditions
@javascript
Scenario: Show section greyed-out to student when completion condition is not satisfied
Given I log in as "teacher1"
And I am on "Course 1" course homepage with editing mode on
And I navigate to "Settings" in current page administration
And I set the following fields to these values:
| Enable completion tracking | Yes |
And I press "Save and display"
And the following "activities" exist:
Given the following "activities" exist:
| activity | course | section | intro | completion | idnumber |
| label | C1 | 1 | Test label | 1 | 1 |
And I log in as "teacher1"
And I am on "Course 1" course homepage with editing mode on
When I edit the section "2"
And I expand all fieldsets
And I click on "Add restriction..." "button"
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -8,6 +8,6 @@ define("core_courseformat/local/courseindex/cm",["exports","core_courseformat/lo
* @class core_courseformat/local/courseindex/cm
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_dndcmitem=_interopRequireDefault(_dndcmitem),_templates=_interopRequireDefault(_templates),_prefetch=_interopRequireDefault(_prefetch),_config=_interopRequireDefault(_config);_prefetch.default.prefetchTemplate("core_courseformat/local/courseindex/cmcompletion");class Component extends _dndcmitem.default{create(){this.name="courseindex_cm",this.selectors={CM_NAME:"[data-for='cm_name']",CM_COMPLETION:"[data-for='cm_completion']"},this.classes={CMHIDDEN:"dimmed",LOCKED:"editinprogress",RESTRICTIONS:"restrictions",PAGEITEM:"pageitem",INDENTED:"indented"},this.id=this.element.dataset.id}static init(target,selectors){return new Component({element:document.getElementById(target),selectors:selectors})}stateReady(state){this.configDragDrop(this.id);const cm=state.cm.get(this.id),course=state.course;this._refreshCompletion({state:state,element:cm});const anchor=new URL(window.location.href).hash.replace("#","");(window.location.href==cm.url||window.location.href.includes(course.baseurl)&&anchor==cm.anchor)&&(this.reactive.dispatch("setPageItem","cm",this.id),this.element.scrollIntoView({block:"center"})),_config.default.contextid!=_config.default.courseContextId&&_config.default.contextInstanceId==this.id&&(this.reactive.dispatch("setPageItem","cm",this.id,!0),this.element.scrollIntoView({block:"center"})),cm.uservisible||this.addEventListener(this.getElement(this.selectors.CM_NAME),"click",this._activityAnchor)}getWatchers(){return[{watch:"cm[".concat(this.id,"]:deleted"),handler:this.remove},{watch:"cm[".concat(this.id,"]:updated"),handler:this._refreshCm},{watch:"cm[".concat(this.id,"].completionstate:updated"),handler:this._refreshCompletion},{watch:"course.pageItem:updated",handler:this._refreshPageItem}]}_refreshCm(_ref){var _element$dragging,_element$locked,_element$hascmrestric;let{element:element}=_ref;this.element.classList.toggle(this.classes.CMHIDDEN,!element.visible),this.getElement(this.selectors.CM_NAME).innerHTML=element.name,this.element.classList.toggle(this.classes.DRAGGING,null!==(_element$dragging=element.dragging)&&void 0!==_element$dragging&&_element$dragging),this.element.classList.toggle(this.classes.LOCKED,null!==(_element$locked=element.locked)&&void 0!==_element$locked&&_element$locked),this.element.classList.toggle(this.classes.RESTRICTIONS,null!==(_element$hascmrestric=element.hascmrestrictions)&&void 0!==_element$hascmrestric&&_element$hascmrestric),this.element.classList.toggle(this.classes.INDENTED,element.indent),this.locked=element.locked}_refreshPageItem(_ref2){let{element:element}=_ref2;if(!element.pageItem)return;const isPageId="cm"==element.pageItem.type&&element.pageItem.id==this.id;this.element.classList.toggle(this.classes.PAGEITEM,isPageId),isPageId&&!this.reactive.isEditing&&this.element.scrollIntoView({block:"nearest"})}async _refreshCompletion(_ref3){let{state:state,element:element}=_ref3;if(this.reactive.isEditing||!element.istrackeduser)return;const completionElement=this.getElement(this.selectors.CM_COMPLETION);if(completionElement.dataset.value==element.completionstate)return;const data=this.reactive.getExporter().cmCompletion(state,element);try{const{html:html,js:js}=await _templates.default.renderForPromise("core_courseformat/local/courseindex/cmcompletion",data);_templates.default.replaceNode(completionElement,html,js)}catch(error){throw error}}_activityAnchor(event){const cm=this.reactive.get("cm",this.id);if(document.getElementById(cm.anchor))return void setTimeout((()=>{this.reactive.dispatch("setPageItem","cm",cm.id)}),50);const course=this.reactive.get("course"),section=this.reactive.get("section",cm.sectionid);if(!section)return;const url="".concat(course.baseurl,"&section=").concat(section.number,"#").concat(cm.anchor);event.preventDefault(),window.location=url}}return _exports.default=Component,_exports.default}));
*/Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_dndcmitem=_interopRequireDefault(_dndcmitem),_templates=_interopRequireDefault(_templates),_prefetch=_interopRequireDefault(_prefetch),_config=_interopRequireDefault(_config);_prefetch.default.prefetchTemplate("core_courseformat/local/courseindex/cmcompletion");class Component extends _dndcmitem.default{create(){this.name="courseindex_cm",this.selectors={CM_NAME:"[data-for='cm_name']",CM_COMPLETION:"[data-for='cm_completion']"},this.classes={CMHIDDEN:"dimmed",LOCKED:"editinprogress",RESTRICTIONS:"restrictions",PAGEITEM:"pageitem",INDENTED:"indented"},this.id=this.element.dataset.id}static init(target,selectors){return new Component({element:document.getElementById(target),selectors:selectors})}stateReady(state){this.configDragDrop(this.id);const cm=state.cm.get(this.id),course=state.course;this._refreshCompletion({state:state,element:cm});const anchor=new URL(window.location.href).hash.replace("#","");(window.location.href==cm.url||window.location.href.includes(course.baseurl)&&anchor==cm.anchor)&&(this.reactive.dispatch("setPageItem","cm",this.id),this.element.scrollIntoView({block:"center"})),_config.default.contextid!=_config.default.courseContextId&&_config.default.contextInstanceId==this.id&&(this.reactive.dispatch("setPageItem","cm",this.id,!0),this.element.scrollIntoView({block:"center"})),cm.uservisible||this.addEventListener(this.getElement(this.selectors.CM_NAME),"click",this._activityAnchor)}getWatchers(){return[{watch:"cm[".concat(this.id,"]:deleted"),handler:this.remove},{watch:"cm[".concat(this.id,"]:updated"),handler:this._refreshCm},{watch:"cm[".concat(this.id,"].completionstate:updated"),handler:this._refreshCompletion},{watch:"course.pageItem:updated",handler:this._refreshPageItem}]}_refreshCm(_ref){var _element$dragging,_element$locked,_element$hascmrestric;let{element:element}=_ref;this.element.classList.toggle(this.classes.CMHIDDEN,!element.visible),this.getElement(this.selectors.CM_NAME).innerHTML=element.name,this.element.classList.toggle(this.classes.DRAGGING,null!==(_element$dragging=element.dragging)&&void 0!==_element$dragging&&_element$dragging),this.element.classList.toggle(this.classes.LOCKED,null!==(_element$locked=element.locked)&&void 0!==_element$locked&&_element$locked),this.element.classList.toggle(this.classes.RESTRICTIONS,null!==(_element$hascmrestric=element.hascmrestrictions)&&void 0!==_element$hascmrestric&&_element$hascmrestric),this.element.classList.toggle(this.classes.INDENTED,element.indent),this.locked=element.locked}_refreshPageItem(_ref2){let{element:element}=_ref2;if(!element.pageItem)return;const isPageId="cm"==element.pageItem.type&&element.pageItem.id==this.id;this.element.classList.toggle(this.classes.PAGEITEM,isPageId),isPageId&&!this.reactive.isEditing&&this.element.scrollIntoView({block:"nearest"})}async _refreshCompletion(_ref3){let{state:state,element:element}=_ref3;if(this.reactive.isEditing||!element.istrackeduser)return;const completionElement=this.getElement(this.selectors.CM_COMPLETION);if(completionElement.dataset.value==element.completionstate)return;const data=this.reactive.getExporter().cmCompletion(state,element),{html:html,js:js}=await _templates.default.renderForPromise("core_courseformat/local/courseindex/cmcompletion",data);_templates.default.replaceNode(completionElement,html,js)}_activityAnchor(event){const cm=this.reactive.get("cm",this.id);if(document.getElementById(cm.anchor))return void setTimeout((()=>{this.reactive.dispatch("setPageItem","cm",cm.id)}),50);const course=this.reactive.get("course"),section=this.reactive.get("section",cm.sectionid);if(!section)return;const url="".concat(course.baseurl,"&section=").concat(section.number,"#").concat(cm.anchor);event.preventDefault(),window.location=url}}return _exports.default=Component,_exports.default}));
//# sourceMappingURL=cm.min.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6 -9
View File
@@ -173,15 +173,12 @@ export default class Component extends BaseComponent {
const toggler = section.querySelector(this.selectors.COLLAPSE);
const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;
if (isChevron || isCollapsed) {
// Update the state.
const sectionId = section.getAttribute('data-id');
this.reactive.dispatch(
'sectionContentCollapsed',
[sectionId],
!isCollapsed
);
}
const sectionId = section.getAttribute('data-id');
this.reactive.dispatch(
'sectionContentCollapsed',
[sectionId],
!isCollapsed,
);
}
}
@@ -0,0 +1,549 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* The course file uploader.
*
* This module is used to upload files directly into the course.
*
* @module core_courseformat/local/courseeditor/fileuploader
* @copyright 2022 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* @typedef {Object} Handler
* @property {String} extension the handled extension or * for any
* @property {String} message the handler message
* @property {String} module the module name
*/
import Config from 'core/config';
import ModalFactory from 'core/modal_factory';
import ModalEvents from 'core/modal_events';
import Templates from 'core/templates';
import {getFirst} from 'core/normalise';
import {prefetchStrings} from 'core/prefetch';
import {get_string as getString, get_strings as getStrings} from 'core/str';
import {getCourseEditor} from 'core_courseformat/courseeditor';
import {processMonitor} from 'core/process_monitor';
import {debounce} from 'core/utils';
// Uploading url.
const UPLOADURL = Config.wwwroot + '/course/dndupload.php';
const DEBOUNCETIMER = 500;
const USERCANIGNOREFILESIZELIMITS = -1;
/** @var {ProcessQueue} uploadQueue the internal uploadQueue instance. */
let uploadQueue = null;
/** @var {Object} handlerManagers the courseId indexed loaded handler managers. */
let handlerManagers = {};
/** @var {Map} courseUpdates the pending course sections updates. */
let courseUpdates = new Map();
/** @var {Object} errors the error messages. */
let errors = null;
// Load global strings.
prefetchStrings('moodle', ['addresourceoractivity', 'upload']);
prefetchStrings('core_error', ['dndmaxbytes', 'dndread', 'dndupload', 'dndunkownfile']);
/**
* Class to upload a file into the course.
* @private
*/
class FileUploader {
/**
* Class constructor.
*
* @param {number} courseId the course id
* @param {number} sectionId the section id
* @param {number} sectionNum the section number
* @param {File} fileInfo the file information object
* @param {Handler} handler the file selected file handler
*/
constructor(courseId, sectionId, sectionNum, fileInfo, handler) {
this.courseId = courseId;
this.sectionId = sectionId;
this.sectionNum = sectionNum;
this.fileInfo = fileInfo;
this.handler = handler;
}
/**
* Execute the file upload and update the state in the given process.
*
* @param {LoadingProcess} process the process to store the upload result
*/
execute(process) {
const fileInfo = this.fileInfo;
const xhr = this._createXhrRequest(process);
const formData = this._createUploadFormData();
// Try reading the file to check it is not a folder, before sending it to the server.
const reader = new FileReader();
reader.onload = function() {
// File was read OK - send it to the server.
xhr.open("POST", UPLOADURL, true);
xhr.send(formData);
};
reader.onerror = function() {
// Unable to read the file (it is probably a folder) - display an error message.
process.setError(errors.dndread);
};
if (fileInfo.size > 0) {
// If this is a non-empty file, try reading the first few bytes.
// This will trigger reader.onerror() for folders and reader.onload() for ordinary, readable files.
reader.readAsText(fileInfo.slice(0, 5));
} else {
// If you call slice() on a 0-byte folder, before calling readAsText, then Firefox triggers reader.onload(),
// instead of reader.onerror().
// So, for 0-byte files, just call readAsText on the whole file (and it will trigger load/error functions as expected).
reader.readAsText(fileInfo);
}
}
/**
* Returns the bind version of execute function.
*
* This method is used to queue the process into a ProcessQueue instance.
*
* @returns {Function} the bind function to execute the process
*/
getExecutionFunction() {
return this.execute.bind(this);
}
/**
* Generate a upload XHR file request.
*
* @param {LoadingProcess} process the current process
* @return {XMLHttpRequest} the XHR request
*/
_createXhrRequest(process) {
const xhr = new XMLHttpRequest();
// Update the progress bar as the file is uploaded.
xhr.upload.addEventListener(
'progress',
(event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded * 100) / event.total);
process.setPercentage(percent);
}
},
false
);
// Wait for the AJAX call to complete.
xhr.onreadystatechange = () => {
if (xhr.readyState == 1) {
// Add a 1% just to indicate that it is uploading.
process.setPercentage(1);
}
// State 4 is DONE. Otherwise the connection is still ongoing.
if (xhr.readyState != 4) {
return;
}
if (xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
if (result && result.error == 0) {
// All OK.
this._finishProcess(process);
} else {
process.setError(result.error);
}
} else {
process.setError(errors.dndupload);
}
};
return xhr;
}
/**
* Upload a file into the course.
*
* @return {FormData|null} the new form data object
*/
_createUploadFormData() {
const formData = new FormData();
try {
formData.append('repo_upload_file', this.fileInfo);
} catch (error) {
throw Error(error.dndread);
}
formData.append('sesskey', Config.sesskey);
formData.append('course', this.courseId);
formData.append('section', this.sectionNum);
formData.append('module', this.handler.module);
formData.append('type', 'Files');
return formData;
}
/**
* Finishes the current process.
* @param {LoadingProcess} process the process
*/
_finishProcess(process) {
addRefreshSection(this.courseId, this.sectionId);
process.setPercentage(100);
process.finish();
}
}
/**
* The file handler manager class.
*
* @private
*/
class HandlerManager {
/** @var {Object} lastHandlers the last handlers selected per each file extension. */
lastHandlers = {};
/** @var {Handler[]|null} allHandlers all the available handlers. */
allHandlers = null;
/**
* Class constructor.
*
* @param {Number} courseId
*/
constructor(courseId) {
this.courseId = courseId;
this.lastUploadId = 0;
this.courseEditor = getCourseEditor(courseId);
if (!this.courseEditor) {
throw Error('Unkown course editor');
}
this.maxbytes = this.courseEditor.get('course')?.maxbytes ?? 0;
}
/**
* Load the course file handlers.
*/
async loadHandlers() {
this.allHandlers = await this.courseEditor.getFileHandlersPromise();
}
/**
* Extract the file extension from a fileInfo.
*
* @param {File} fileInfo
* @returns {String} the file extension or an empty string.
*/
getFileExtension(fileInfo) {
let extension = '';
const dotpos = fileInfo.name.lastIndexOf('.');
if (dotpos != -1) {
extension = fileInfo.name.substring(dotpos + 1, fileInfo.name.length).toLowerCase();
}
return extension;
}
/**
* Check if the file is valid.
*
* @param {File} fileInfo the file info
*/
validateFile(fileInfo) {
if (this.maxbytes !== USERCANIGNOREFILESIZELIMITS && fileInfo.size > this.maxbytes) {
throw Error(errors.dndmaxbytes);
}
}
/**
* Get the file handlers of an specific file.
*
* @param {File} fileInfo the file indo
* @return {Array} Array of handlers
*/
filterHandlers(fileInfo) {
const extension = this.getFileExtension(fileInfo);
return this.allHandlers.filter(handler => handler.extension == '*' || handler.extension == extension);
}
/**
* Get the Handler to upload a specific file.
*
* It will ask the used if more than one handler is available.
*
* @param {File} fileInfo the file info
* @returns {Promise<Handler|null>} the selected handler or null if the user cancel
*/
async getFileHandler(fileInfo) {
const fileHandlers = this.filterHandlers(fileInfo);
if (fileHandlers.length == 0) {
throw Error(errors.dndunkownfile);
}
let fileHandler = null;
if (fileHandlers.length == 1) {
fileHandler = fileHandlers[0];
} else {
fileHandler = await this.askHandlerToUser(fileHandlers, fileInfo);
}
return fileHandler;
}
/**
* Ask the user to select a specific handler.
*
* @param {Handler[]} fileHandlers
* @param {File} fileInfo the file info
* @return {Promise<Handler>} the selected handler
*/
async askHandlerToUser(fileHandlers, fileInfo) {
const extension = this.getFileExtension(fileInfo);
// Build the modal parameters from the event data.
const modalParams = {
title: getString('addresourceoractivity', 'moodle'),
body: Templates.render(
'core_courseformat/fileuploader',
this.getModalData(
fileHandlers,
fileInfo,
this.lastHandlers[extension] ?? null
)
),
type: ModalFactory.types.SAVE_CANCEL,
saveButtonText: getString('upload', 'moodle'),
};
// Create the modal.
const modal = await this.modalBodyRenderedPromise(modalParams);
const selectedHandler = await this.modalUserAnswerPromise(modal, fileHandlers);
// Cancel action.
if (selectedHandler === null) {
return null;
}
// Save last selected handler.
this.lastHandlers[extension] = selectedHandler.module;
return selectedHandler;
}
/**
* Generated the modal template data.
*
* @param {Handler[]} fileHandlers
* @param {File} fileInfo the file info
* @param {String|null} defaultModule the default module if any
* @return {Object} the modal template data.
*/
getModalData(fileHandlers, fileInfo, defaultModule) {
const data = {
filename: fileInfo.name,
uploadid: ++this.lastUploadId,
handlers: [],
};
let hasDefault = false;
fileHandlers.forEach((handler, index) => {
const isDefault = (defaultModule == handler.module);
data.handlers.push({
...handler,
selected: isDefault,
labelid: `fileuploader_${data.uploadid}`,
value: index,
});
hasDefault = hasDefault || isDefault;
});
if (!hasDefault && data.handlers.length > 0) {
const lastHandler = data.handlers.pop();
lastHandler.selected = true;
data.handlers.push(lastHandler);
}
return data;
}
/**
* Get the user handler choice.
*
* Wait for the user answer in the modal and resolve with the selected index.
*
* @param {Modal} modal the modal instance
* @param {Handler[]} fileHandlers the availabvle file handlers
* @return {Promise} with the option selected by the user.
*/
modalUserAnswerPromise(modal, fileHandlers) {
const modalBody = getFirst(modal.getBody());
return new Promise((resolve, reject) => {
modal.getRoot().on(
ModalEvents.save,
event => {
// Get the selected option.
const index = modalBody.querySelector('input:checked').value;
event.preventDefault();
modal.destroy();
if (!fileHandlers[index]) {
reject('Invalid handler selected');
}
resolve(fileHandlers[index]);
}
);
modal.getRoot().on(
ModalEvents.cancel,
() => {
resolve(null);
}
);
});
}
/**
* Create a new modal and return a Promise to the body rendered.
*
* @param {Object} modalParams the modal params
* @returns {Promise} the modal body rendered promise
*/
modalBodyRenderedPromise(modalParams) {
return new Promise((resolve, reject) => {
ModalFactory.create(modalParams).then((modal) => {
modal.setRemoveOnClose(true);
// Handle body loading event.
modal.getRoot().on(ModalEvents.bodyRendered, () => {
resolve(modal);
});
// Configure some extra modal params.
if (modalParams.saveButtonText !== undefined) {
modal.setSaveButtonText(modalParams.saveButtonText);
}
modal.show();
return;
}).catch(() => {
reject(`Cannot load modal content`);
});
});
}
}
/**
* Add a section to refresh.
*
* @param {number} courseId the course id
* @param {number} sectionId the seciton id
*/
function addRefreshSection(courseId, sectionId) {
let refresh = courseUpdates.get(courseId);
if (!refresh) {
refresh = new Set();
}
refresh.add(sectionId);
courseUpdates.set(courseId, refresh);
refreshCourseEditors();
}
/**
* Debounced processing all pending course refreshes.
* @private
*/
const refreshCourseEditors = debounce(
() => {
const refreshes = courseUpdates;
courseUpdates = new Map();
refreshes.forEach((sectionIds, courseId) => {
const courseEditor = getCourseEditor(courseId);
if (!courseEditor) {
return;
}
courseEditor.dispatch('sectionState', [...sectionIds]);
});
},
DEBOUNCETIMER
);
/**
* Load and return the course handler manager instance.
*
* @param {Number} courseId the course Id to load
* @returns {Promise<HandlerManager>} promise of the the loaded handleManager
*/
async function loadCourseHandlerManager(courseId) {
if (handlerManagers[courseId] !== undefined) {
return handlerManagers[courseId];
}
const handlerManager = new HandlerManager(courseId);
await handlerManager.loadHandlers();
handlerManagers[courseId] = handlerManager;
return handlerManagers[courseId];
}
/**
* Load all the erros messages at once in the module "errors" variable.
* @param {Number} courseId the course id
*/
async function loadErrorStrings(courseId) {
if (errors !== null) {
return;
}
const courseEditor = getCourseEditor(courseId);
const maxbytestext = courseEditor.get('course')?.maxbytestext ?? '0';
errors = {};
const allStrings = [
{key: 'dndmaxbytes', component: 'core_error', param: {size: maxbytestext}},
{key: 'dndread', component: 'core_error'},
{key: 'dndupload', component: 'core_error'},
{key: 'dndunkownfile', component: 'core_error'},
];
window.console.log(allStrings);
const loadedStrings = await getStrings(allStrings);
allStrings.forEach(({key}, index) => {
errors[key] = loadedStrings[index];
});
}
/**
* Start a batch file uploading into the course.
*
* @private
* @param {number} courseId the course id.
* @param {number} sectionId the section id.
* @param {number} sectionNum the section number.
* @param {File} fileInfo the file information object
* @param {HandlerManager} handlerManager the course handler manager
*/
const queueFileUpload = async function(courseId, sectionId, sectionNum, fileInfo, handlerManager) {
let handler;
uploadQueue = await processMonitor.createProcessQueue();
try {
handlerManager.validateFile(fileInfo);
handler = await handlerManager.getFileHandler(fileInfo);
} catch (error) {
uploadQueue.addError(fileInfo.name, error.message);
return;
}
// If we don't have a handler means the user cancel the upload.
if (!handler) {
return;
}
const fileProcessor = new FileUploader(courseId, sectionId, sectionNum, fileInfo, handler);
uploadQueue.addPending(fileInfo.name, fileProcessor.getExecutionFunction());
};
/**
* Upload a file to the course.
*
* This method will show any necesary modal to handle the request.
*
* @param {number} courseId the course id
* @param {number} sectionId the section id
* @param {number} sectionNum the section number
* @param {Array} files and array of files
*/
export const uploadFilesToCourse = async function(courseId, sectionId, sectionNum, files) {
// Get the course handlers.
const handlerManager = await loadCourseHandlerManager(courseId);
await loadErrorStrings(courseId);
for (let index = 0; index < files.length; index++) {
const fileInfo = files[index];
await queueFileUpload(courseId, sectionId, sectionNum, fileInfo, handlerManager);
}
};
@@ -473,12 +473,16 @@ export default class {
* @param {boolean} collapsed the new collapsed value
*/
async sectionIndexCollapsed(stateManager, sectionIds, collapsed) {
const collapsedIds = this._updateStateSectionPreference(stateManager, 'indexcollapsed', sectionIds, collapsed);
if (!collapsedIds) {
const affectedSections = this._updateStateSectionPreference(stateManager, 'indexcollapsed', sectionIds, collapsed);
if (!affectedSections) {
return;
}
const course = stateManager.get('course');
await this._callEditWebservice('section_index_collapsed', course.id, collapsedIds);
let actionName = 'section_index_collapsed';
if (!collapsed) {
actionName = 'section_index_expanded';
}
await this._callEditWebservice(actionName, course.id, affectedSections);
}
/**
@@ -489,12 +493,16 @@ export default class {
* @param {boolean} collapsed the new collapsed value
*/
async sectionContentCollapsed(stateManager, sectionIds, collapsed) {
const collapsedIds = this._updateStateSectionPreference(stateManager, 'contentcollapsed', sectionIds, collapsed);
if (!collapsedIds) {
const affectedSections = this._updateStateSectionPreference(stateManager, 'contentcollapsed', sectionIds, collapsed);
if (!affectedSections) {
return;
}
const course = stateManager.get('course');
await this._callEditWebservice('section_content_collapsed', course.id, collapsedIds);
let actionName = 'section_content_collapsed';
if (!collapsed) {
actionName = 'section_content_expanded';
}
await this._callEditWebservice(actionName, course.id, affectedSections);
}
/**
@@ -508,32 +516,22 @@ export default class {
*/
_updateStateSectionPreference(stateManager, preferenceName, sectionIds, preferenceValue) {
stateManager.setReadOnly(false);
const affectedSections = new Set();
const affectedSections = [];
// Check if we need to update preferences.
sectionIds.forEach(sectionId => {
const section = stateManager.get('section', sectionId);
if (section === undefined) {
stateManager.setReadOnly(true);
return null;
}
const newValue = preferenceValue ?? section[preferenceName];
if (section[preferenceName] != newValue) {
section[preferenceName] = newValue;
affectedSections.add(section.id);
affectedSections.push(section.id);
}
});
stateManager.setReadOnly(true);
if (affectedSections.size == 0) {
return null;
}
// Get all collapsed section ids.
const collapsedSectionIds = [];
const state = stateManager.state;
state.section.forEach(section => {
if (section[preferenceName]) {
collapsedSectionIds.push(section.id);
}
});
return collapsedSectionIds;
return affectedSections;
}
/**
@@ -180,12 +180,8 @@ export default class Component extends DndCmItem {
const exporter = this.reactive.getExporter();
const data = exporter.cmCompletion(state, element);
try {
const {html, js} = await Templates.renderForPromise(completionTemplate, data);
Templates.replaceNode(completionElement, html, js);
} catch (error) {
throw error;
}
const {html, js} = await Templates.renderForPromise(completionTemplate, data);
Templates.replaceNode(completionElement, html, js);
}
/**
@@ -131,9 +131,16 @@ export default class Component extends BaseComponent {
const toggler = section.querySelector(this.selectors.COLLAPSE);
const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;
if (isChevron || isCollapsed) {
// Update the state.
const sectionId = section.getAttribute('data-id');
// Update the state.
const sectionId = section.getAttribute('data-id');
if ((!sectionlink)) {
this.reactive.dispatch(
'sectionIndexCollapsed',
[sectionId],
!isCollapsed
);
} else if (isCollapsed) {
// Always expand the section when clicking on section name.
this.reactive.dispatch(
'sectionIndexCollapsed',
[sectionId],
+60 -4
View File
@@ -617,8 +617,9 @@ abstract class base {
global $USER;
$course = $this->get_course();
try {
$sectionpreferences = (array) json_decode(
get_user_preferences("coursesectionspreferences_{$course->id}", '', $USER->id)
$sectionpreferences = json_decode(
get_user_preferences("coursesectionspreferences_{$course->id}", '', $USER->id),
true
);
if (empty($sectionpreferences)) {
$sectionpreferences = [];
@@ -637,10 +638,65 @@ abstract class base {
*
*/
public function set_sections_preference(string $preferencename, array $sectionids) {
global $USER;
$course = $this->get_course();
$sectionpreferences = $this->get_sections_preferences_by_preference();
$sectionpreferences[$preferencename] = $sectionids;
$this->persist_to_user_preference($sectionpreferences);
}
/**
* Add section preference ids.
*
* @param string $preferencename preference name
* @param array $sectionids affected section ids
*/
public function add_section_preference_ids(
string $preferencename,
array $sectionids
): void {
$sectionpreferences = $this->get_sections_preferences_by_preference();
if (!isset($sectionpreferences[$preferencename])) {
$sectionpreferences[$preferencename] = [];
}
foreach ($sectionids as $sectionid) {
if (!in_array($sectionid, $sectionpreferences[$preferencename])) {
$sectionpreferences[$preferencename][] = $sectionid;
}
}
$this->persist_to_user_preference($sectionpreferences);
}
/**
* Remove section preference ids.
*
* @param string $preferencename preference name
* @param array $sectionids affected section ids
*/
public function remove_section_preference_ids(
string $preferencename,
array $sectionids
): void {
$sectionpreferences = $this->get_sections_preferences_by_preference();
if (!isset($sectionpreferences[$preferencename])) {
$sectionpreferences[$preferencename] = [];
}
foreach ($sectionids as $sectionid) {
if (($key = array_search($sectionid, $sectionpreferences[$preferencename])) !== false) {
unset($sectionpreferences[$preferencename][$key]);
}
}
$this->persist_to_user_preference($sectionpreferences);
}
/**
* Persist the section preferences to the user preferences.
*
* @param array $sectionpreferences the section preferences
*/
private function persist_to_user_preference(
array $sectionpreferences
): void {
global $USER;
$course = $this->get_course();
set_user_preference('coursesectionspreferences_' . $course->id, json_encode($sectionpreferences), $USER->id);
// Invalidate section preferences cache.
$coursesectionscache = cache::make('core', 'coursesectionspreferences');
+50 -4
View File
@@ -531,7 +531,7 @@ class stateactions {
}
/**
* Update the course content section collapsed value.
* Update the course content section state to collapse.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
@@ -550,11 +550,34 @@ class stateactions {
$this->validate_sections($course, $ids, __FUNCTION__);
}
$format = course_get_format($course->id);
$format->set_sections_preference('contentcollapsed', $ids);
$format->add_section_preference_ids('contentcollapsed', $ids);
}
/**
* Update the course index section collapsed value.
* Update the course content section state to expand.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the collapsed section ids
* @param int|null $targetsectionid not used
* @param int|null $targetcmid not used
*/
public function section_content_expanded(
stateupdates $updates,
stdClass $course,
array $ids = [],
?int $targetsectionid = null,
?int $targetcmid = null
): void {
if (!empty($ids)) {
$this->validate_sections($course, $ids, __FUNCTION__);
}
$format = course_get_format($course->id);
$format->remove_section_preference_ids('contentcollapsed', $ids);
}
/**
* Update the course index section state to collapse.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
@@ -573,7 +596,30 @@ class stateactions {
$this->validate_sections($course, $ids, __FUNCTION__);
}
$format = course_get_format($course->id);
$format->set_sections_preference('indexcollapsed', $ids);
$format->add_section_preference_ids('indexcollapsed', $ids);
}
/**
* Update the course index section state to expand.
*
* @param stateupdates $updates the affected course elements track
* @param stdClass $course the course object
* @param int[] $ids the collapsed section ids
* @param int $targetsectionid not used
* @param int $targetcmid not used
*/
public function section_index_expanded(
stateupdates $updates,
stdClass $course,
array $ids = [],
?int $targetsectionid = null,
?int $targetcmid = null
): void {
if (!empty($ids)) {
$this->validate_sections($course, $ids, __FUNCTION__);
}
$format = course_get_format($course->id);
$format->remove_section_preference_ids('indexcollapsed', $ids);
}
/**
+67
View File
@@ -347,6 +347,73 @@ class base_test extends advanced_testcase {
);
}
/**
* Test add_section_preference_ids() method.
*
* @covers \core_courseformat\base::persist_to_user_preference
*/
public function test_add_section_preference_ids(): void {
$this->resetAfterTest();
// Create initial data.
$generator = $this->getDataGenerator();
$course = $generator->create_course();
$user = $generator->create_and_enrol($course);
// Get the course format.
$format = course_get_format($course);
// Login as the user.
$this->setUser($user);
// Add section preference ids.
$format->add_section_preference_ids('pref1', [1, 2]);
$format->add_section_preference_ids('pref1', [3]);
$format->add_section_preference_ids('pref2', [1]);
// Get section preferences.
$sectionpreferences = $format->get_sections_preferences_by_preference();
$this->assertCount(3, $sectionpreferences['pref1']);
$this->assertContains(1, $sectionpreferences['pref1']);
$this->assertContains(2, $sectionpreferences['pref1']);
$this->assertContains(3, $sectionpreferences['pref1']);
$this->assertCount(1, $sectionpreferences['pref2']);
$this->assertContains(1, $sectionpreferences['pref1']);
}
/**
* Test remove_section_preference_ids() method.
*
* @covers \core_courseformat\base::persist_to_user_preference
*/
public function test_remove_section_preference_ids(): void {
$this->resetAfterTest();
// Create initial data.
$generator = $this->getDataGenerator();
$course = $generator->create_course();
$user = $generator->create_and_enrol($course);
// Get the course format.
$format = course_get_format($course);
// Login as the user.
$this->setUser($user);
// Set initial preferences.
$format->set_sections_preference('pref1', [1, 2, 3]);
$format->set_sections_preference('pref2', [1]);
// Remove section with id = 3 out of the pref1.
$format->remove_section_preference_ids('pref1', [3]);
// Get section preferences.
$sectionpreferences = $format->get_sections_preferences_by_preference();
$this->assertCount(2, $sectionpreferences['pref1']);
$this->assertCount(1, $sectionpreferences['pref2']);
// Remove section with id = 2 out of the pref1.
$format->remove_section_preference_ids('pref1', [2]);
// Remove section with id = 1 out of the pref2.
$format->remove_section_preference_ids('pref2', [1]);
// Get section preferences.
$sectionpreferences = $format->get_sections_preferences_by_preference();
$this->assertCount(1, $sectionpreferences['pref1']);
$this->assertEmpty($sectionpreferences['pref2']);
}
/**
* Test that retrieving last section number for a course
*
+4
View File
@@ -2,6 +2,10 @@ This files describes API changes for course formats
Overview of this plugin type at https://moodledev.io/docs/apis/plugintypes/format
=== 4.1.10 ===
* New core_courseformat\base::add_section_preference_ids() to add the section ids to course format preferences.
* New core_courseformat\base::remove_section_preference_ids() to remove the section ids out of course format preferences.
=== 4.1 ===
* New \core_courseformat\stateupdates methods add_section_remove() and add_cm_remove() have been added to replace
the deprecated methods add_section_delete() and add_cm_delete().
+8 -12
View File
@@ -11,9 +11,8 @@ Feature: Add activities to courses
@javascript
Scenario: Add an activity to a course
Given I am on the "Course 1" Course page logged in as admin
And I am on "Course 1" course homepage with editing mode on
When I add a "Database" to section "3" and I fill the form with:
Given I log in as "admin"
When I add a data activity to course "Course 1" section "3" and I fill the form with:
| Name | Test name |
| Description | Test database description |
| ID number | TESTNAME |
@@ -32,9 +31,8 @@ Feature: Add activities to courses
@javascript
Scenario: Add an activity supplying only the name
Given I am on the "Course 1" Course page logged in as admin
And I am on "Course 1" course homepage with editing mode on
When I add a "Database" to section "3" and I fill the form with:
Given I log in as "admin"
When I add a data activity to course "Course 1" section "3" and I fill the form with:
| Name | Test name |
Then I should see "Test name"
@@ -42,9 +40,8 @@ Feature: Add activities to courses
Scenario: Set activity description to required then add an activity supplying only the name
Given the following config values are set as admin:
| requiremodintro | 1 |
And I am on the "Course 1" Course page logged in as admin
And I am on "Course 1" course homepage with editing mode on
And I add a "Database" to section "3" and I fill the form with:
And I log in as "admin"
And I add a data activity to course "Course 1" section "3" and I fill the form with:
| Name | Test name |
Then I should see "Required"
@@ -53,9 +50,8 @@ Feature: Add activities to courses
Given the following "user preferences" exist:
| user | preference | value |
| admin | htmleditor | textarea |
And I am logged in as admin
And I am on "Course 1" course homepage with editing mode on
When I add a "Database" to section "3"
And I log in as "admin"
When I add a data activity to course "Course 1" section "3"
Then the field "Description format" matches value "0"
@javascript
+111 -5
View File
@@ -202,7 +202,7 @@ class behat_course extends behat_base {
if ($section) {
// Section 1 represents the contents on the frontpage.
$sectionxpath = "//body[@id='page-site-index']" .
"/descendant::div[contains(concat(' ',normalize-space(@class),' '),' sitetopic ')]";
"/descendant::div[contains(concat(' ',normalize-space(@class),' '),' sitetopic ')]";
} else {
// Section 0 represents "Site main menu" block.
$sectionxpath = "//*[contains(concat(' ',normalize-space(@class),' '),' block_site_main_menu ')]";
@@ -224,10 +224,116 @@ class behat_course extends behat_base {
// Clicks the selected activity if it exists.
$activityliteral = behat_context_helper::escape(ucfirst($activity));
$activityxpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' modchooser ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optioninfo ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optionname ')]" .
"[normalize-space(.)=$activityliteral]" .
"/parent::a";
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optioninfo ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optionname ')]" .
"[normalize-space(.)=$activityliteral]" .
"/parent::a";
$this->execute('behat_general::i_click_on', [$activityxpath, 'xpath']);
}
/**
* Adds the selected activity/resource filling the form data with the specified field/value pairs.
*
* Sections 0 and 1 are also allowed on frontpage.
*
* @Given I add a :activity activity to course :coursefullname section :sectionnum and I fill the form with:
* @Given I add an :activity activity to course :coursefullname section :sectionnum and I fill the form with:
* @param string $activity The activity name
* @param string $coursefullname The course full name of the course.
* @param int $section The section number
* @param TableNode $data The activity field/value data
*/
public function i_add_to_course_section_and_i_fill_the_form_with($activity, $coursefullname, $section, TableNode $data) {
// Add activity to section.
$this->execute(
"behat_course::i_add_to_course_section",
[$this->escape($activity), $this->escape($coursefullname), $this->escape($section)]
);
// Wait to be redirected.
$this->execute('behat_general::wait_until_the_page_is_ready');
// Set form fields.
$this->execute("behat_forms::i_set_the_following_fields_to_these_values", $data);
// Save course settings.
$this->execute("behat_forms::press_button", get_string('savechangesandreturntocourse'));
}
/**
* Open a add activity form page.
*
* @Given I add a :activity activity to course :coursefullname section :sectionnum
* @Given I add an :activity activity to course :coursefullname section :sectionnum
* @throws coding_exception
* @param string $activity The activity name.
* @param string $coursefullname The course full name of the course.
* @param string $sectionnum The section number.
*/
public function i_add_to_course_section(string $activity, string $coursefullname, string $sectionnum): void {
$addurl = new moodle_url('/course/modedit.php', [
'add' => $activity,
'course' => $this->get_course_id($coursefullname),
'section' => intval($sectionnum),
]);
$this->execute('behat_general::i_visit', [$addurl]);
}
/**
* Opens the activity chooser and opens the activity/resource link form page.
*
* Sections 0 and 1 are also allowed on frontpage.
*
* This step require javascript enabled and it is used mainly to click activities or resources by name,
* not by plugin name. Use the standard behat_course::i_add_to_course_section step instead unless the
* plugin create extra entries into the activity chooser (like LTI).
*
* @Given I add a :activityname to section :sectionnum using the activity chooser
* @Given I add an :activityname to section :sectionnum using the activity chooser
* @throws ElementNotFoundException Thrown by behat_base::find
* @param string $activityname
* @param int $sectionnum
*/
public function i_add_to_section_using_the_activity_chooser($activityname, $sectionnum) {
$this->require_javascript('Please use the \'the following "activity" exists:\' data generator instead.');
if ($this->getSession()->getPage()->find('css', 'body#page-site-index') && (int) $sectionnum <= 1) {
// We are on the frontpage.
if ($sectionnum) {
// Section 1 represents the contents on the frontpage.
$sectionxpath = "//body[@id='page-site-index']" .
"/descendant::div[contains(concat(' ',normalize-space(@class),' '),' sitetopic ')]";
} else {
// Section 0 represents "Site main menu" block.
$sectionxpath = "//*[contains(concat(' ',normalize-space(@class),' '),' block_site_main_menu ')]";
}
} else {
// We are inside the course.
$sectionxpath = "//li[@id='section-" . $sectionnum . "']";
}
// Clicks add activity or resource section link.
$sectionnode = $this->find('xpath', $sectionxpath);
$this->execute(
'behat_general::i_click_on_in_the',
[
"//button[@data-action='open-chooser' and not(@data-beforemod)]",
'xpath',
$sectionnode,
'NodeElement',
]
);
// Clicks the selected activity if it exists.
$activityliteral = behat_context_helper::escape(ucfirst($activityname));
$activityxpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' modchooser ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optioninfo ')]" .
"/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' optionname ')]" .
"[normalize-space(.)=$activityliteral]" .
"/parent::a";
$this->execute('behat_general::i_click_on', [$activityxpath, 'xpath']);
}
@@ -0,0 +1,38 @@
@core_course
Feature: Force course language
To be able to force a language for the course
As a teacher
I need to be able to set force language setting for the course
Background:
Given remote langimport tests are enabled
And the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | One | teacher1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
And the following "language pack" exists:
| language | fr | es |
Scenario: A teacher can set a course language
Given I am on the "Course 1" course page logged in as "teacher1"
# Site default language is English.
And I should see "Settings"
And I follow "Preferences" in the user menu
And I follow "Preferred language"
# Change preferred language to French.
And I set the field "Preferred language" to "fr"
And I press "Save changes"
And I am on "Course 1" course homepage
And I should see "Paramètres"
# Change course language to Spanish.
And I navigate to "Paramètres" in current page administration
When I set the following fields to these values:
| id_lang | es |
And I press "Enregistrer et afficher"
# Course language is now Spanish.
Then I should see "Configuración"
@@ -10,8 +10,8 @@ Feature: Show/hide course sections
| teacher1 | Teacher | 1 | teacher1@example.com |
| student1 | Student | 1 | student1@example.com |
And the following "courses" exist:
| fullname | shortname | format | hiddensections |
| Course 1 | C1 | topics | 0 |
| fullname | shortname | format | hiddensections | enablecompletion | coursedisplay |
| Course 1 | C1 | topics | 0 | 1 | 1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
@@ -76,12 +76,7 @@ Feature: Show/hide course sections
@javascript
Scenario: Students can not navigate to restricted sections
Given I navigate to "Settings" in current page administration
And I set the following fields to these values:
| Course layout | Show one section per page |
| Enable completion tracking | Yes |
And I press "Save and display"
And the following "activities" exist:
Given the following "activities" exist:
| activity | course | section | name | completion |
| label | C1 | 1 | Test label | 1 |
And I edit the section "2"
+4
View File
@@ -2,6 +2,10 @@ This files describes API changes in /course/*,
information provided here is intended especially for developers.
=== 4.1.7 ===
* New behat steps backported to stable versions:
- I add a :activityname to section :sectionnum using the activity chooser
- I add a :activitypluginname activity to course :coursefullname section :sectionnum
- I add a :activitypluginname activity to course :coursefullname section :sectionnum and I fill the form with:
* set_coursemodule_visible() has a new $rebuildcache parameter. If this is being called multiple times in the same request,
consider passing `false` for this parameter and rebuilding the cache once after all the course modules have been updated.
See course_update_section() for an example.
+20 -9
View File
@@ -619,6 +619,7 @@ class core_enrol_external extends external_api {
'searchanywhere' => new external_value(PARAM_BOOL, 'find a match anywhere, or only at the beginning'),
'page' => new external_value(PARAM_INT, 'Page number'),
'perpage' => new external_value(PARAM_INT, 'Number per page'),
'contextid' => new external_value(PARAM_INT, 'Context ID', VALUE_DEFAULT, null),
]
);
}
@@ -631,11 +632,12 @@ class core_enrol_external extends external_api {
* @param bool $searchanywhere Match anywhere in the string
* @param int $page Page number
* @param int $perpage Max per page
* @param ?int $contextid Context ID we are in - we might use search on activity level and its group mode can be different from course group mode.
* @return array An array of users
* @throws moodle_exception
*/
public static function search_users(int $courseid, string $search, bool $searchanywhere, int $page, int $perpage): array {
global $PAGE, $DB, $CFG;
public static function search_users(int $courseid, string $search, bool $searchanywhere, int $page, int $perpage, ?int $contextid = null): array {
global $PAGE, $CFG;
require_once($CFG->dirroot.'/enrol/locallib.php');
require_once($CFG->dirroot.'/user/lib.php');
@@ -647,10 +649,15 @@ class core_enrol_external extends external_api {
'search' => $search,
'searchanywhere' => $searchanywhere,
'page' => $page,
'perpage' => $perpage
]
'perpage' => $perpage,
'contextid' => $contextid,
],
);
$context = context_course::instance($params['courseid']);
if (isset($contextid)) {
$context = context::instance_by_id($params['contextid']);
} else {
$context = context_course::instance($params['courseid']);
}
try {
self::validate_context($context);
} catch (Exception $e) {
@@ -664,10 +671,14 @@ class core_enrol_external extends external_api {
$course = get_course($params['courseid']);
$manager = new course_enrolment_manager($PAGE, $course);
$users = $manager->search_users($params['search'],
$params['searchanywhere'],
$params['page'],
$params['perpage']);
$users = $manager->search_users(
$params['search'],
$params['searchanywhere'],
$params['page'],
$params['perpage'],
false,
$params['contextid']
);
$results = [];
// Add also extra user fields.
+18 -4
View File
@@ -563,26 +563,40 @@ class course_enrolment_manager {
* @param int $page Starting at 0.
* @param int $perpage Number of users returned per page.
* @param bool $returnexactcount Return the exact total users using count_record or not.
* @param ?int $contextid Context ID we are in - we might use search on activity level and its group mode can be different from course group mode.
* @return array with two or three elements:
* int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
* array users List of user objects returned by the query.
* boolean moreusers True if there are still more users, otherwise is False.
*/
public function search_users(string $search = '', bool $searchanywhere = false, int $page = 0, int $perpage = 25,
bool $returnexactcount = false) {
bool $returnexactcount = false, ?int $contextid = null) {
global $USER;
[$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
$groupmode = groups_get_course_groupmode($this->course);
if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $this->context)) {
if (isset($contextid)) {
// If contextid is set, we need to determine the group mode that should be used (module or course).
[$context, $course, $cm] = get_context_info_array($contextid);
// If cm instance is returned, then use the group mode from the module, otherwise get the course group mode.
$groupmode = $cm ? groups_get_activity_groupmode($cm, $course) : groups_get_course_groupmode($this->course);
} else {
// Otherwise, default to the group mode of the course.
$context = $this->context;
$groupmode = groups_get_course_groupmode($this->course);
}
if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $context)) {
$groups = groups_get_all_groups($this->course->id, $USER->id, 0, 'g.id');
$groupids = array_column($groups, 'id');
if (!$groupids) {
return ['totalusers' => 0, 'users' => [], 'moreusers' => false];
}
} else {
$groupids = [];
}
[$enrolledsql, $enrolledparams] = get_enrolled_sql($this->context, '', $groupids);
[$enrolledsql, $enrolledparams] = get_enrolled_sql($context, '', $groupids);
$fields = 'SELECT ' . $ufields;
$countfields = 'SELECT COUNT(u.id)';
+15
View File
@@ -263,4 +263,19 @@ class renderer extends plugin_renderer_base {
return parent::render_from_template('enrol_lti/local/ltiadvantage/registration_view',
$tcontext);
}
/**
* Render a warning, indicating to the user that cookies are require but couldn't be set.
*
* @return string the html.
*/
public function render_cookies_required_notice(): string {
$notification = new notification(get_string('cookiesarerequiredinfo', 'enrol_lti'), notification::NOTIFY_WARNING, false);
$tcontext = [
'heading' => get_string('cookiesarerequired', 'enrol_lti'),
'notification' => $notification->export_for_template($this),
];
return parent::render_from_template('enrol_lti/local/ltiadvantage/cookies_required_notice', $tcontext);
}
}
+4
View File
@@ -31,6 +31,10 @@ $string['addtocourse'] = 'Add to course';
$string['addtogradebook'] = 'Add to gradebook';
$string['allowframeembedding'] = 'Note: It is recommended that the site administration setting \'Allow frame embedding\' is enabled, so that tools are displayed within a frame rather than in a new window.';
$string['authltimustbeenabled'] = 'Note: This plugin requires the LTI authentication plugin to be enabled too.';
$string['cookiesarerequired'] = 'Cookies are blocked by your browser';
$string['cookiesarerequiredinfo'] = 'This tool can\'t be launched because your browser seems to be blocking third-party cookies.
<br><br>
To use this tool, try changing your browser cookie settings or using a different browser.';
$string['copiedtoclipboard'] = '{$a} copied to clipboard';
$string['copytoclipboard'] = 'Copy to clipboard';
$string['couldnotestablishproxy'] = 'Could not establish proxy with consumer.';
+26 -1
View File
@@ -26,6 +26,7 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use auth_lti\local\ltiadvantage\utility\cookie_helper;
use enrol_lti\local\ltiadvantage\lib\issuer_database;
use enrol_lti\local\ltiadvantage\lib\launch_cache_session;
use enrol_lti\local\ltiadvantage\repository\application_registration_repository;
@@ -39,7 +40,7 @@ require_once(__DIR__."/../../config.php");
// See http://www.imsglobal.org/spec/security/v1p0/#step-1-third-party-initiated-login.
// Validate these here, despite further validation in the LTI 1.3 library.
$iss = required_param('iss', PARAM_URL); // Issuer URI of the calling platform.
$loginhint = required_param('login_hint', PARAM_INT); // Platform ID for the person to login.
$loginhint = required_param('login_hint', PARAM_RAW); // Platform ID for the person to login.
$targetlinkuri = required_param('target_link_uri', PARAM_URL); // The took launch URL.
// Optional lti_message_hint. See https://www.imsglobal.org/spec/lti/v1p3#additional-login-parameters-0.
@@ -76,6 +77,30 @@ if (empty($_REQUEST['client_id']) && !empty($_REQUEST['id'])) {
$_REQUEST['client_id'] = $_REQUEST['id'];
}
// Before beginning the OIDC authentication, ensure the MoodleSession cookie can be used. Browser-specific steps may need to be
// taken to set cookies in 3rd party contexts. Skip the check if the user is already auth'd. This means that either cookies aren't
// an issue in the current browser/launch context.
if (!isloggedin()) {
cookie_helper::do_cookie_check(new moodle_url('/enrol/lti/login.php', [
'iss' => $iss,
'login_hint' => $loginhint,
'target_link_uri' => $targetlinkuri,
'lti_message_hint' => $ltimessagehint,
'client_id' => $_REQUEST['client_id'],
]));
if (!cookie_helper::cookies_supported()) {
global $OUTPUT, $PAGE;
$PAGE->set_context(context_system::instance());
$PAGE->set_url(new moodle_url('/enrol/lti/login.php'));
$PAGE->set_pagelayout('popup');
echo $OUTPUT->header();
$renderer = $PAGE->get_renderer('enrol_lti');
echo $renderer->render_cookies_required_notice();
echo $OUTPUT->footer();
die();
}
}
// Now, do the OIDC login.
LtiOidcLogin::new(
new issuer_database(new application_registration_repository(), new deployment_repository()),
@@ -0,0 +1,50 @@
{{!
This file is part of Moodle - http://moodle.org/
Moodle is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Moodle is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Moodle. If not, see <http://www.gnu.org/licenses/>.
}}
{{!
@template enrol_lti/local/ltiadvantage/cookies_required_notice
Displays a notice, reporting that cookies are required but couldn't be set.
Classes required for JS:
* none
Data attributes required for JS:
* none
Context variables required for this template:
* heading
* notification
Example context (json):
{
"heading": "Cookies are required",
"notification": {
"message": "You appear to be using an unsupported browser...",
"extraclasses": "",
"announce": true,
"closebutton": false,
"issuccess": false,
"isinfo": false,
"iswarning": true,
"iserror": false
}
}
}}
<h3>{{heading}}</h3>
{{#notification}}
{{> core/notification}}
{{/notification}}
+56 -13
View File
@@ -18,6 +18,7 @@ namespace core_enrol;
use context_course;
use course_enrolment_manager;
use stdClass;
/**
* Test course_enrolment_manager parts.
@@ -557,11 +558,18 @@ class course_enrolment_manager_test extends \advanced_testcase {
$this->resetAfterTest();
// Create the forum.
$record = new stdClass();
$record->introformat = FORMAT_HTML;
$record->course = $this->course->id;
$forum = self::getDataGenerator()->create_module('forum', $record, ['groupmode' => SEPARATEGROUPS]);
$contextid = $DB->get_field('context', 'id', ['instanceid' => $forum->cmid, 'contextlevel' => CONTEXT_MODULE]);
$teacher = $this->getDataGenerator()->create_and_enrol($this->course, 'teacher');
$this->getDataGenerator()->create_group_member(['groupid' => $this->groups['group1']->id, 'userid' => $teacher->id]);
$this->setUser($teacher);
$users = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true);
$courseusers = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true);
$this->assertEqualsCanonicalizing([
$teacher->username,
$this->users['user0']->username,
@@ -570,26 +578,49 @@ class course_enrolment_manager_test extends \advanced_testcase {
$this->users['user22']->username,
$this->users['userall']->username,
$this->users['usertch']->username,
], array_column($users['users'], 'username'));
$this->assertEquals(7, $users['totalusers']);
], array_column($courseusers['users'], 'username'));
$this->assertEquals(7, $courseusers['totalusers']);
// Switch course to separate groups.
$this->course->groupmode = SEPARATEGROUPS;
update_course($this->course);
$users = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true);
$forumusers = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true, $contextid);
$this->assertEqualsCanonicalizing([
$teacher->username,
$this->users['user1']->username,
$this->users['userall']->username,
], array_column($users['users'], 'username'));
$this->assertEquals(3, $users['totalusers']);
], array_column($forumusers['users'], 'username'));
$this->assertEquals(3, $forumusers['totalusers']);
// Switch course to separate groups and forum to no group.
$this->course->groupmode = SEPARATEGROUPS;
update_course($this->course);
set_coursemodule_groupmode($forum->cmid, NOGROUPS);
$courseusers = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true);
$this->assertEqualsCanonicalizing([
$teacher->username,
$this->users['user1']->username,
$this->users['userall']->username,
], array_column($courseusers['users'], 'username'));
$this->assertEquals(3, $courseusers['totalusers']);
$forumusers = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true, $contextid);
$this->assertEqualsCanonicalizing([
$teacher->username,
$this->users['user0']->username,
$this->users['user1']->username,
$this->users['user21']->username,
$this->users['user22']->username,
$this->users['userall']->username,
$this->users['usertch']->username,
], array_column($forumusers['users'], 'username'));
$this->assertEquals(7, $forumusers['totalusers']);
set_coursemodule_groupmode($forum->cmid, SEPARATEGROUPS);
// Allow teacher to access all groups.
$roleid = $DB->get_field('role', 'id', ['shortname' => 'teacher']);
assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $roleid, context_course::instance($this->course->id)->id);
$users = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true);
$courseusers = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true);
$this->assertEqualsCanonicalizing([
$teacher->username,
$this->users['user0']->username,
@@ -598,7 +629,19 @@ class course_enrolment_manager_test extends \advanced_testcase {
$this->users['user22']->username,
$this->users['userall']->username,
$this->users['usertch']->username,
], array_column($users['users'], 'username'));
$this->assertEquals(7, $users['totalusers']);
], array_column($courseusers['users'], 'username'));
$this->assertEquals(7, $courseusers['totalusers']);
$forumusers = (new course_enrolment_manager($PAGE, $this->course))->search_users('', false, 0, 25, true, $contextid);
$this->assertEqualsCanonicalizing([
$teacher->username,
$this->users['user0']->username,
$this->users['user1']->username,
$this->users['user21']->username,
$this->users['user22']->username,
$this->users['userall']->username,
$this->users['usertch']->username,
], array_column($forumusers['users'], 'username'));
$this->assertEquals(7, $forumusers['totalusers']);
}
}
+66
View File
@@ -19,6 +19,7 @@ namespace core_enrol;
use core_enrol_external;
use enrol_user_enrolment_form;
use externallib_advanced_testcase;
use stdClass;
defined('MOODLE_INTERNAL') || die();
@@ -1402,6 +1403,71 @@ class externallib_test extends externallib_advanced_testcase {
$this->assertCount(0, $result);
}
/**
* Test for core_enrol_external::search_users() when group mode is active.
* @covers ::search_users
*/
public function test_search_users_groupmode() {
global $DB;
$this->resetAfterTest();
$datagen = $this->getDataGenerator();
$studentroleid = $DB->get_field('role', 'id', ['shortname' => 'student'], MUST_EXIST);
$teacherroleid = $DB->get_field('role', 'id', ['shortname' => 'teacher'], MUST_EXIST);
$course = $datagen->create_course();
$student1 = $datagen->create_and_enrol($course);
$student2 = $datagen->create_and_enrol($course);
$student3 = $datagen->create_and_enrol($course);
$teacher1 = $datagen->create_and_enrol($course, 'teacher');
$teacher2 = $datagen->create_and_enrol($course, 'teacher');
$teacher3 = $datagen->create_and_enrol($course, 'teacher');
$teacher4 = $datagen->create_and_enrol($course, 'editingteacher');
// Create 2 groups.
$group1 = $datagen->create_group(['courseid' => $course->id]);
$group2 = $datagen->create_group(['courseid' => $course->id]);
// Add the users to the groups.
$datagen->create_group_member(['groupid' => $group1->id, 'userid' => $student1->id]);
$datagen->create_group_member(['groupid' => $group2->id, 'userid' => $student2->id]);
$datagen->create_group_member(['groupid' => $group2->id, 'userid' => $student3->id]);
$datagen->create_group_member(['groupid' => $group1->id, 'userid' => $teacher1->id]);
$datagen->create_group_member(['groupid' => $group2->id, 'userid' => $teacher1->id]);
$datagen->create_group_member(['groupid' => $group1->id, 'userid' => $teacher2->id]);
// Create the forum.
$record = new stdClass();
$record->introformat = FORMAT_HTML;
$record->course = $course->id;
$forum = self::getDataGenerator()->create_module('forum', $record, ['groupmode' => SEPARATEGROUPS]);
$contextid = $DB->get_field('context', 'id', ['instanceid' => $forum->cmid, 'contextlevel' => CONTEXT_MODULE]);
$this->setUser($teacher1);
$result = core_enrol_external::search_users($course->id, 'user', true, 0, 30, $contextid);
$this->assertCount(5, $result);
$this->setUser($teacher2);
$result = core_enrol_external::search_users($course->id, 'user', true, 0, 30, $contextid);
$this->assertCount(3, $result);
$this->setUser($teacher3);
$result = core_enrol_external::search_users($course->id, 'user', true, 0, 30, $contextid);
$this->assertCount(0, $result);
$this->setUser($teacher4);
$result = core_enrol_external::search_users($course->id, 'user', true, 0, 30, $contextid);
$this->assertCount(7, $result);
// Now change the group mode to no groups.
set_coursemodule_groupmode($forum->cmid, NOGROUPS);
$this->setUser($teacher1);
$result = core_enrol_external::search_users($course->id, 'user', true, 0, 30, $contextid);
$this->assertCount(7, $result);
}
/**
* Tests the get_potential_users external function (not too much detail because the back-end
* is covered in another test).
+5
View File
@@ -1,6 +1,11 @@
This files describes API changes in /enrol/* - plugins,
information provided here is intended especially for developers.
=== 4.1.9 ===
* Functions core_enrol_external::search_users and course_enrolment_manager::search_users now have extra optional parameter
contextid which allows to search users in a specific activity context. When omitted it searches in the whole course.
=== 4.1.1 ===
* New is_self_enrol_available() function has been created. Similar to can_self_enrol but without checking user capabilities.
@@ -1,4 +1,4 @@
/* stylelint-disable unit-blacklist */
/* stylelint-disable unit-disallowed-list */
/**************************************
Structure of the other user role assignment panel
+20
View File
@@ -138,9 +138,13 @@ class filter_mathjaxloader extends moodle_text_filter {
$hasdisplayorinline = false;
if ($hasextra) {
// Convert the HTML tag wrapper inside the equation to entities.
$text = $this->escape_html_tag_wrapper($text);
// If custom dilimeters are used, wrap whole text to prevent autolinking.
$text = '<span class="nolink">' . $text . '</span>';
} else if (preg_match('/\\\\[[(]/', $text) || preg_match('/\$\$/', $text)) {
// Convert the HTML tag wrapper inside the equation to entities.
$text = $this->escape_html_tag_wrapper($text);
// Only parse the text if there are mathjax symbols in it. The recognized
// math environments are \[ \] and $$ $$ for display mathematics and \( \)
// for inline mathematics.
@@ -246,4 +250,20 @@ class filter_mathjaxloader extends moodle_text_filter {
$start,
$end - $start + 1);
}
/**
* Escapes HTML tags within a string.
*
* This function replaces HTML tags enclosed in curly brackets with their respective HTML entities.
*
* @param string $text The input string containing HTML tags.
* @return string Returns the input string with HTML tags escaped.
*/
private function escape_html_tag_wrapper(string $text): string {
return preg_replace_callback('/\{([^}]+)\}/', function(array $matches): string {
$search = ['<', '>'];
$replace = ['&lt;', '&gt;'];
return str_replace($search, $replace, $matches[0]);
}, $text);
}
}
@@ -0,0 +1,72 @@
@gradingform @gradingform_guide @javascript
Feature: Display marking guide information to students
In order for students to see the marking guide information
As a teacher
I should be able to change display settings for marking guide information
Background:
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | 1 | teacher1@example.com |
| student1 | Student | 1 | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activities" exist:
| activity | course | name | advancedgradingmethod_submissions |
| assign | C1 | Assign 1 | guide |
And I am on the "Course 1" course page logged in as teacher1
And I go to "Assign 1" advanced grading definition page
And I set the following fields to these values:
| Name | Assign 1 marking guide |
| Description | Marking guide description |
And I define the following marking guide:
| Criterion name | Description for students | Description for markers | Maximum score |
| Grade Criteria 1 | Grade 1 description for students | Grade 1 description for markers | 70 |
| Grade Criteria 2 | Grade 2 description for students | Grade 2 description for markers | 30 |
And I press "Save marking guide and make it ready"
Scenario: Confirm that marking guide information is not displayed after student is graded
# Update the existing marking guide to ensure that marks per criterion is displayed.
Given I click on "Edit the current form definition" "link"
And I set the field "Show marks per criterion to students" to "0"
And I press "Save"
And I am on the "Assign 1" "assign activity" page
And I go to "Student 1" "Assign 1" activity advanced grading page
And I grade by filling the marking guide with:
| Grade Criteria 1 | 50 | Excellent work! |
| Grade Criteria 2 | 20 | Try harder |
And I press "Save changes"
When I am on the "Assign 1" "assign activity" page logged in as student1
# Confirm the marking guide information display after student is graded when marking per criterion display is disabled.
# Confirm that overall grade is displayed.
Then I should see "70.00 / 100.00"
And I should see the marking guide information displayed as:
| criteria | description | remark |
| Grade Criteria 1 | Grade 1 description for students | Excellent work! |
| Grade Criteria 2 | Grade 2 description for students | Try harder |
Scenario: Confirm that marking guide information is displayed after student is graded
Given I am on the "Assign 1" "assign activity" page logged in as student1
And I should see "Grade 1 description for students" in the "Grade Criteria 1" "table_row"
And I should see "Grade 2 description for students" in the "Grade Criteria 2" "table_row"
# No grade to student1 yet.
And I should not see "70.00 / 100.00"
# No need to update marking guide as marking guide definition is already enabled by default
And I am on the "Assign 1" "assign activity" page logged in as teacher1
And I go to "Student 1" "Assign 1" activity advanced grading page
And I grade by filling the marking guide with:
| Grade Criteria 1 | 50 | Excellent work! |
| Grade Criteria 2 | 20 | Try harder |
And I press "Save changes"
When I am on the "Assign 1" "assign activity" page logged in as student1
# Student1 grade is now displayed.
Then I should see "70.00 / 100.00"
And I should see the marking guide information displayed as:
| criteria | description | remark | maxscore | criteriascore |
| Grade Criteria 1 | Grade 1 description for students | Excellent work! | 70 | 50 / 70 |
| Grade Criteria 2 | Grade 2 description for students | Try harder | 30 | 20 / 30 |
+3 -7
View File
@@ -183,12 +183,7 @@ class graded_users_iterator {
}
}
$userfieldsapi = \core_user\fields::for_identity($coursecontext, false)->with_userpic();
$userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
// This need to be fixed - webservices in grade/report/user/classes/external/user.php don't check permission properly.
$userfields .= ', u.idnumber, u.institution, u.department';
$userfields = 'u.*';
$customfieldssql = '';
if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
$customfieldscount = 0;
@@ -222,7 +217,8 @@ class graded_users_iterator {
$this->users_rs = $DB->get_recordset_sql($users_sql, $params);
if (!$this->onlyactive) {
$this->suspendedusers = get_suspended_userids($coursecontext);
$context = context_course::instance($this->course->id);
$this->suspendedusers = get_suspended_userids($context);
} else {
$this->suspendedusers = array();
}
@@ -27,36 +27,36 @@ Feature: Teacher can navigate to the previous or next user report.
Scenario: A teacher can navigate to the next user report
Given I click on "Student 1" in the "user" search widget
And I should see "Student 1" in the ".user-heading" "css_element"
And "Student 1" "heading" should exist
And ".previous" "css_element" should not exist in the ".user-navigation" "css_element"
And ".next" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 2" in the ".next" "css_element"
When I click on "Student 2" "link" in the ".next" "css_element"
Then I should see "Student 2" in the ".user-heading" "css_element"
And "Student 2" "heading" should exist
And ".previous" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 1" in the ".previous" "css_element"
And ".next" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 3" in the ".next" "css_element"
And I click on "Student 3" "link" in the ".next" "css_element"
And I should see "Student 3" in the ".user-heading" "css_element"
And "Student 3" "heading" should exist
And ".previous" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 2" in the ".previous" "css_element"
And ".next" "css_element" should not exist in the ".user-navigation" "css_element"
Scenario: A teacher can navigate to the previous user report
Given I click on "Student 3" in the "user" search widget
And I should see "Student 3" in the ".user-heading" "css_element"
And "Student 3" "heading" should exist
And ".previous" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 2" in the ".previous" "css_element"
And ".next" "css_element" should not exist in the ".user-navigation" "css_element"
When I click on "Student 2" "link" in the ".previous" "css_element"
Then I should see "Student 2" in the ".user-heading" "css_element"
And "Student 2" "heading" should exist
And ".previous" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 1" in the ".previous" "css_element"
And ".next" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 3" in the ".next" "css_element"
And I click on "Student 1" "link" in the ".previous" "css_element"
And I should see "Student 1" in the ".user-heading" "css_element"
And "Student 1" "heading" should exist
And ".previous" "css_element" should not exist in the ".user-navigation" "css_element"
And ".next" "css_element" should exist in the ".user-navigation" "css_element"
And I should see "Student 2" in the ".next" "css_element"
@@ -0,0 +1,52 @@
@core @core_grades @javascript
Feature: Admin can set Recover grades default setting
In order to recover grades
As an admin
I need to enable "Recover grades default" from site administration
Background:
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | One | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| student1 | C1 | student |
And the following "activities" exist:
| activity | course | name |
| assign | C1 | Assign 1 |
Scenario Outline: Recover grades default setting can be changed
Given the following config values are set as admin:
| recovergradesdefault | <recovergradesetting> |
# Grade student 1 via quick grading
And I am on the "Assign 1" "assign activity" page logged in as admin
And I follow "View all submissions"
And I click on "Quick grading" "checkbox"
And I set the field "User grade" to "60.00"
And I press "Save all quick grading changes"
# Confirm that assigned grade was saved
And I am on the "Course 1" "grades > Grader report > View" page
And I should see "60.00" in the "Student One" "table_row"
And I navigate to course participants
And I click on "Unenrol" "icon" in the "Student One" "table_row"
And I click on "Unenrol" "button" in the "Unenrol" "dialogue"
# The button at the top is hidden by the un-enrolment confirmation dialogue so the button at the bottom is clicked instead.
And I click on "Enrol users" "button" in the "div.justify-content-end .enrolusersbutton" "css_element"
And I set the field "Select users" to "student1"
# Confirm the "Recover user's old grades if possible" checkbox state based on Recover grades default setting
When I click on "Show more..." "link"
Then the field "Recover user's old grades if possible" matches value "<oldgraderecover>"
# Confirm that "Recover user's old grades if possible" checkbox state can be changed manually
And I click on "Recover user's old grades if possible" "checkbox" in the "Enrol users" "dialogue"
And I click on "Enrol users" "button" in the "Enrol users" "dialogue"
# Confirm whether re-enrolled student's grade is recovered or not based on student enrolment settings
And I am on the "Course 1" "grades > Grader report > View" page
And I <gradevisibility> see "60.00" in the "Student One" "table_row"
Examples:
| recovergradesetting | oldgraderecover | gradevisibility |
| 0 | 0 | should |
| 1 | 1 | should not |

Some files were not shown because too many files have changed in this diff Show More