weekly release 3.10+
[moodle.git] / lib / behat / behat_base.php
CommitLineData
d4322e38
DM
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Base class of all steps definitions.
19 *
20 * This script is only called from Behat as part of it's integration
21 * in Moodle.
22 *
23 * @package core
24 * @category test
25 * @copyright 2012 David MonllaĆ³
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
30
7bfb575f
AN
31use Behat\Mink\Exception\DriverException;
32use Behat\Mink\Exception\ExpectationException;
33use Behat\Mink\Exception\ElementNotFoundException;
34use Behat\Mink\Element\NodeElement;
700682dc 35use Behat\Mink\Element\Element;
7bfb575f 36use Behat\Mink\Session;
ff48a235 37
61832fae
AN
38require_once(__DIR__ . '/classes/component_named_selector.php');
39require_once(__DIR__ . '/classes/component_named_replacement.php');
40
d4322e38
DM
41/**
42 * Steps definitions base class.
43 *
44 * To extend by the steps definitions of the different Moodle components.
45 *
46 * It can not contain steps definitions to avoid duplicates, only utility
47 * methods shared between steps.
48 *
fcb6ed47
MG
49 * @method NodeElement find_field(string $locator) Finds a form element
50 * @method NodeElement find_button(string $locator) Finds a form input submit element or a button
51 * @method NodeElement find_link(string $locator) Finds a link on a page
52 * @method NodeElement find_file(string $locator) Finds a forum input file element
53 *
d4322e38
DM
54 * @package core
55 * @category test
56 * @copyright 2012 David MonllaĆ³
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 */
59class behat_base extends Behat\MinkExtension\Context\RawMinkContext {
60
74c78e74
DM
61 /**
62 * Small timeout.
63 *
64 * A reduced timeout for cases where self::TIMEOUT is too much
65 * and a simple $this->getSession()->getPage()->find() could not
66 * be enough.
05a5d547 67 *
68 * @deprecated since Moodle 3.7 MDL-64979 - please use get_reduced_timeout() instead
84524186 69 * @todo MDL-64982 This will be deleted in Moodle 3.11
05a5d547 70 * @see behat_base::get_reduced_timeout()
74c78e74
DM
71 */
72 const REDUCED_TIMEOUT = 2;
73
d4322e38
DM
74 /**
75 * The timeout for each Behat step (load page, wait for an element to load...).
05a5d547 76 *
77 * @deprecated since Moodle 3.7 MDL-64979 - please use get_timeout() instead
84524186 78 * @todo MDL-64982 This will be deleted in Moodle 3.11
05a5d547 79 * @see behat_base::get_timeout()
d4322e38 80 */
845ceaff 81 const TIMEOUT = 6;
d1e55a47
DM
82
83 /**
84 * And extended timeout for specific cases.
05a5d547 85 *
86 * @deprecated since Moodle 3.7 MDL-64979 - please use get_extended_timeout() instead
84524186 87 * @todo MDL-64982 This will be deleted in Moodle 3.11
05a5d547 88 * @see behat_base::get_extended_timeout()
d1e55a47
DM
89 */
90 const EXTENDED_TIMEOUT = 10;
91
d1e55a47
DM
92 /**
93 * The JS code to check that the page is ready.
d8892dcc
NDM
94 *
95 * The document must be complete and either M.util.pending_js must be empty, or it must not be defined at all.
d1e55a47 96 */
d8892dcc
NDM
97 const PAGE_READY_JS = "document.readyState === 'complete' && " .
98 "(typeof M !== 'object' || typeof M.util !== 'object' || " .
99 "typeof M.util.pending_js === 'undefined' || M.util.pending_js.length === 0)";
d4322e38 100
786ea937
DM
101 /**
102 * Locates url, based on provided path.
103 * Override to provide custom routing mechanism.
104 *
105 * @see Behat\MinkExtension\Context\MinkContext
106 * @param string $path
107 * @return string
108 */
40923977 109 protected function locate_path($path) {
46ac40cd
DM
110 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
111 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
112 }
113
ff48a235 114 /**
f8f1bdc3 115 * Returns the first matching element.
ff48a235
DM
116 *
117 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
118 * @param string $selector The selector type (css, xpath, named...)
119 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 120 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 121 * @param NodeElement $node Spins around certain DOM node instead of the whole page
74c78e74 122 * @param int $timeout Forces a specific time out (in seconds).
ff48a235
DM
123 * @return NodeElement
124 */
74c78e74 125 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
34503872
AN
126 if ($selector === 'NodeElement' && is_a($locator, NodeElement::class)) {
127 // Support a NodeElement being passed in for use in step chaining.
128 return $locator;
129 }
130
f8f1bdc3 131 // Returns the first match.
74c78e74 132 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
f8f1bdc3
DM
133 return count($items) ? reset($items) : null;
134 }
135
136 /**
137 * Returns all matching elements.
138 *
139 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
140 *
141 * @link http://mink.behat.org/#traverse-the-page-selectors
142 * @param string $selector The selector type (css, xpath, named...)
143 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
144 * @param Exception $exception Otherwise we throw expcetion with generic info
700682dc 145 * @param NodeElement $container Restrict the search to just children of the specified container
74c78e74 146 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
f8f1bdc3
DM
147 * @return array NodeElements list
148 */
700682dc 149 protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) {
42ad096f
RT
150 // Throw exception, so dev knows it is not supported.
151 if ($selector === 'named') {
152 $exception = 'Using the "named" selector is deprecated as of 3.1. '
153 .' Use the "named_partial" or use the "named_exact" selector instead.';
154 throw new ExpectationException($exception, $this->getSession());
155 }
156
ff48a235
DM
157 // Generic info.
158 if (!$exception) {
ff48a235 159 // With named selectors we can be more specific.
07298309 160 if (($selector == 'named_exact') || ($selector == 'named_partial')) {
ff48a235
DM
161 $exceptiontype = $locator[0];
162 $exceptionlocator = $locator[1];
0a7f6a02
DM
163
164 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 165 if ($this->running_javascript()) {
0a7f6a02
DM
166 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
167 }
168
ff48a235
DM
169 } else {
170 $exceptiontype = $selector;
171 $exceptionlocator = $locator;
172 }
173
174 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
175 }
176
74c78e74
DM
177 // How much we will be waiting for the element to appear.
178 if (!$timeout) {
05a5d547 179 $timeout = self::get_timeout();
74c78e74
DM
180 $microsleep = false;
181 } else {
182 // Spinning each 0.1 seconds if the timeout was forced as we understand
183 // that is a special case and is good to refine the performance as much
184 // as possible.
185 $microsleep = true;
186 }
187
700682dc
AN
188 // Normalise the values in order to perform the search.
189 [
190 'selector' => $selector,
191 'locator' => $locator,
192 'container' => $container,
193 ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage());
194
ff48a235
DM
195 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
196 return $this->spin(
700682dc
AN
197 function() use ($selector, $locator, $container) {
198 return $container->findAll($selector, $locator);
199 }, [], $timeout, $exception, $microsleep
200 );
201 }
072f67fc 202
700682dc
AN
203 /**
204 * Normalise the locator and selector.
205 *
206 * @param string $selector The type of thing to search
207 * @param mixed $locator The locator value. Can be an array, but is more likely a string.
208 * @param Element $container An optional container to search within
209 * @return array The selector, locator, and container to search within
210 */
211 public function normalise_selector(string $selector, $locator, Element $container): array {
b983ae4a
AN
212 // Check for specific transformations for this selector type.
213 $transformfunction = "transform_find_for_{$selector}";
214 if (method_exists('behat_selectors', $transformfunction)) {
215 // A selector-specific transformation exists.
216 // Perform initial transformation of the selector within the current container.
217 [
218 'selector' => $selector,
219 'locator' => $locator,
220 'container' => $container,
221 ] = behat_selectors::{$transformfunction}($this, $locator, $container);
222 }
223
700682dc
AN
224 // Normalise the css and xpath selector types.
225 if ('css_element' === $selector) {
226 $selector = 'css';
227 } else if ('xpath_element' === $selector) {
228 $selector = 'xpath';
229 }
072f67fc 230
61832fae 231 // Convert to a named selector where the selector type is not a known selector.
700682dc
AN
232 $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector);
233 $converttonamed = $converttonamed && 'xpath' !== $selector;
234 if ($converttonamed) {
61832fae
AN
235 if (behat_partial_named_selector::is_deprecated_selector($selector)) {
236 if ($replacement = behat_partial_named_selector::get_deprecated_replacement($selector)) {
237 error_log("The '{$selector}' selector has been replaced with {$replacement}");
238 $selector = $replacement;
239 }
240 } else if (behat_exact_named_selector::is_deprecated_selector($selector)) {
241 if ($replacement = behat_exact_named_selector::get_deprecated_replacement($selector)) {
242 error_log("The '{$selector}' selector has been replaced with {$replacement}");
243 $selector = $replacement;
244 }
245 }
246
700682dc
AN
247 $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors();
248 $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors();
249 if (isset($allowedpartialselectors[$selector])) {
250 $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator);
251 $selector = 'named_partial';
252 } else if (isset($allowedexactselectors[$selector])) {
253 $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator);
254 $selector = 'named_exact';
255 } else {
61832fae 256 throw new ExpectationException("The '{$selector}' selector type is not registered.", $this->getSession()->getDriver());
700682dc
AN
257 }
258 }
259
260 return [
261 'selector' => $selector,
262 'locator' => $locator,
263 'container' => $container,
264 ];
ff48a235
DM
265 }
266
267 /**
268 * Finds DOM nodes in the page using named selectors.
269 *
270 * The point of using this method instead of Mink ones is the spin
271 * method of behat_base::find() that looks for the element until it
272 * is available or it timeouts, this avoids the false failures received
273 * when selenium tries to execute commands on elements that are not
274 * ready to be used.
275 *
276 * All steps that requires elements to be available before interact with
277 * them should use one of the find* methods.
278 *
279 * The methods calls requires a {'find_' . $elementtype}($locator)
280 * format, like find_link($locator), find_select($locator),
281 * find_button($locator)...
282 *
283 * @link http://mink.behat.org/#named-selectors
284 * @throws coding_exception
46ac40cd 285 * @param string $name The name of the called method
ff48a235
DM
286 * @param mixed $arguments
287 * @return NodeElement
288 */
289 public function __call($name, $arguments) {
700682dc
AN
290 if (substr($name, 0, 5) === 'find_') {
291 return call_user_func_array([$this, 'find'], array_merge(
292 [substr($name, 5)],
293 $arguments
294 ));
ff48a235
DM
295 }
296
700682dc 297 throw new coding_exception("The '{$name}' method does not exist");
ff48a235
DM
298 }
299
49d91129
DM
300 /**
301 * Escapes the double quote character.
302 *
303 * Double quote is the argument delimiter, it can be escaped
304 * with a backslash, but we auto-remove this backslashes
305 * before the step execution, this method is useful when using
306 * arguments as arguments for other steps.
307 *
308 * @param string $string
309 * @return string
310 */
311 public function escape($string) {
312 return str_replace('"', '\"', $string);
313 }
314
786ea937
DM
315 /**
316 * Executes the passed closure until returns true or time outs.
317 *
318 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
319 * requires more time to be completely loaded or an element to be visible or whatever is required to
320 * perform some action on an element; this method receives a closure which should contain the
321 * required statements to ensure the step definition actions and assertions have all their needs
322 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
323 * closure to the caller.
324 *
325 * The closures requirements to work well with this spin method are:
326 * - Must return false, null or '' if something goes wrong
327 * - Must return something != false if finishes as expected, this will be the (mixed) value
328 * returned by spin()
329 *
ff48a235 330 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 331 *
ff48a235 332 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
c51c3b55 333 * closure exception will be used, but you must provide an exception if the closure does not throw
ff48a235
DM
334 * an exception.
335 *
8e5f86bc
SH
336 * @throws Exception If it timeouts without receiving something != false from the closure
337 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
338 * @param mixed $args Arguments to pass to the closure
339 * @param int $timeout Timeout in seconds
340 * @param Exception $exception The exception to throw in case it time outs.
341 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
342 * @return mixed The value returned by the closure
343 */
8e5f86bc 344 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
345
346 // Using default timeout which is pretty high.
347 if (!$timeout) {
05a5d547 348 $timeout = self::get_timeout();
786ea937
DM
349 }
350
c7807a10
AN
351 $start = microtime(true);
352 $end = $start + $timeout;
80ac8522 353
c7807a10 354 do {
786ea937
DM
355 // We catch the exception thrown by the step definition to execute it again.
356 try {
786ea937 357 // We don't check with !== because most of the time closures will return
ff48a235
DM
358 // direct Behat methods returns and we are not sure it will be always (bool)false
359 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 360 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
361 return $return;
362 }
46ac40cd 363 } catch (Exception $e) {
ff48a235
DM
364 // We would use the first closure exception if no exception has been provided.
365 if (!$exception) {
366 $exception = $e;
367 }
786ea937
DM
368 }
369
c7807a10
AN
370 if (!$this->running_javascript()) {
371 break;
8e5f86bc 372 }
c7807a10
AN
373
374 usleep(100000);
375
376 } while (microtime(true) < $end);
786ea937 377
ff48a235
DM
378 // Using coding_exception as is a development issue if no exception has been provided.
379 if (!$exception) {
8e5f86bc 380 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
381 }
382
786ea937
DM
383 // Throwing exception to the user.
384 throw $exception;
385 }
386
40923977
DM
387 /**
388 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
389 *
072f67fc
DM
390 * Use behat_base::get_text_selector_node() for text-based selectors.
391 *
40923977
DM
392 * @throws ElementNotFoundException Thrown by behat_base::find
393 * @param string $selectortype
394 * @param string $element
395 * @return NodeElement
396 */
397 protected function get_selected_node($selectortype, $element) {
d10ed4d2 398 return $this->find($selectortype, $element);
40923977
DM
399 }
400
072f67fc
DM
401 /**
402 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
403 *
404 * @throws ElementNotFoundException Thrown by behat_base::find
405 * @param string $selectortype
406 * @param string $element
407 * @return NodeElement
408 */
409 protected function get_text_selector_node($selectortype, $element) {
072f67fc
DM
410 // Getting Mink selector and locator.
411 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
412
413 // Returns the NodeElement.
414 return $this->find($selector, $locator);
415 }
416
417 /**
418 * Gets the requested element inside the specified container.
419 *
420 * @throws ElementNotFoundException Thrown by behat_base::find
421 * @param mixed $selectortype The element selector type.
422 * @param mixed $element The element locator.
423 * @param mixed $containerselectortype The container selector type.
424 * @param mixed $containerelement The container locator.
425 * @return NodeElement
426 */
427 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
072f67fc
DM
428 // Gets the container, it will always be text based.
429 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
430
072f67fc
DM
431 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
432 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
433
d10ed4d2 434 return $this->find($selectortype, $element, $exception, $containernode);
072f67fc
DM
435 }
436
40923977
DM
437 /**
438 * Transforms from step definition's argument style to Mink format.
439 *
440 * Mink has 3 different selectors css, xpath and named, where named
441 * selectors includes link, button, field... to simplify and group multiple
442 * steps in one we use the same interface, considering all link, buttons...
443 * at the same level as css selectors and xpath; this method makes the
444 * conversion from the arguments received by the steps to the selectors and locators
445 * required to interact with Mink.
446 *
447 * @throws ExpectationException
448 * @param string $selectortype It can be css, xpath or any of the named selectors.
449 * @param string $element The locator (or string) we are looking for.
450 * @return array Contains the selector and the locator expected by Mink.
451 */
452 protected function transform_selector($selectortype, $element) {
17344d4c
DM
453 // Here we don't know if an allowed text selector is being used.
454 $selectors = behat_selectors::get_allowed_selectors();
455 if (!isset($selectors[$selectortype])) {
40923977
DM
456 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
457 }
458
700682dc
AN
459 [
460 'selector' => $selector,
461 'locator' => $locator,
462 ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage());
463
464 return [$selector, $locator];
40923977
DM
465 }
466
072f67fc
DM
467 /**
468 * Transforms from step definition's argument style to Mink format.
469 *
470 * Delegates all the process to behat_base::transform_selector() checking
471 * the provided $selectortype.
472 *
473 * @throws ExpectationException
474 * @param string $selectortype It can be css, xpath or any of the named selectors.
475 * @param string $element The locator (or string) we are looking for.
476 * @return array Contains the selector and the locator expected by Mink.
477 */
478 protected function transform_text_selector($selectortype, $element) {
479
17344d4c
DM
480 $selectors = behat_selectors::get_allowed_text_selectors();
481 if (empty($selectors[$selectortype])) {
072f67fc
DM
482 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
483 }
484
485 return $this->transform_selector($selectortype, $element);
486 }
487
eff79d53 488 /**
6d5d1935 489 * Whether Javascript is available in the current Session.
eff79d53
DM
490 *
491 * @return boolean
492 */
493 protected function running_javascript() {
6d5d1935
AN
494 return self::running_javascript_in_session($this->getSession());
495 }
496
497 /**
498 * Require that javascript be available in the current Session.
499 *
500 * @throws DriverException
501 */
502 protected function require_javascript() {
503 return self::require_javascript_in_session($this->getSession());
504 }
505
506 /**
507 * Whether Javascript is available in the specified Session.
508 *
509 * @param Session $session
510 * @return boolean
511 */
512 protected static function running_javascript_in_session(Session $session): bool {
513 return get_class($session->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
514 }
515
516 /**
517 * Require that javascript be available for the specified Session.
518 *
519 * @param Session $session
520 * @throws DriverException
521 */
522 protected static function require_javascript_in_session(Session $session): void {
523 if (self::running_javascript_in_session($session)) {
524 return;
525 }
526
527 throw new DriverException('Javascript is required');
eff79d53
DM
528 }
529
079eae37 530 /**
531 * Checks if the current page is part of the mobile app.
532 *
533 * @return bool True if it's in the app
534 */
535 protected function is_in_app() : bool {
536 // Cannot be in the app if there's no @app tag on scenario.
537 if (!$this->has_tag('app')) {
538 return false;
539 }
540
541 // Check on page to see if it's an app page. Safest way is to look for added JavaScript.
cd6eadd4 542 return $this->evaluate_script('return typeof window.behat') === 'object';
079eae37 543 }
544
d1e55a47
DM
545 /**
546 * Spins around an element until it exists
547 *
548 * @throws ExpectationException
d10ed4d2 549 * @param string $locator
d1e55a47
DM
550 * @param string $selectortype
551 * @return void
552 */
d10ed4d2 553 protected function ensure_element_exists($locator, $selectortype) {
d1e55a47 554 // Exception if it timesout and the element is still there.
d10ed4d2 555 $msg = "The '{$locator}' element does not exist and should";
d1e55a47
DM
556 $exception = new ExpectationException($msg, $this->getSession());
557
d10ed4d2
AN
558 // Normalise the values in order to perform the search.
559 [
560 'selector' => $selector,
561 'locator' => $locator,
562 'container' => $container,
563 ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
564
c1faf86b 565 // It will stop spinning once the find() method returns true.
d1e55a47 566 $this->spin(
d10ed4d2
AN
567 function() use ($selector, $locator, $container) {
568 if ($container->find($selector, $locator)) {
d1e55a47
DM
569 return true;
570 }
c1faf86b 571 return false;
d1e55a47 572 },
d10ed4d2 573 [],
05a5d547 574 self::get_extended_timeout(),
d1e55a47
DM
575 $exception,
576 true
577 );
d1e55a47
DM
578 }
579
580 /**
581 * Spins until the element does not exist
582 *
583 * @throws ExpectationException
d10ed4d2 584 * @param string $locator
d1e55a47
DM
585 * @param string $selectortype
586 * @return void
587 */
d10ed4d2 588 protected function ensure_element_does_not_exist($locator, $selectortype) {
d1e55a47 589 // Exception if it timesout and the element is still there.
d10ed4d2 590 $msg = "The '{$locator}' element exists and should not exist";
d1e55a47
DM
591 $exception = new ExpectationException($msg, $this->getSession());
592
d10ed4d2
AN
593 // Normalise the values in order to perform the search.
594 [
595 'selector' => $selector,
596 'locator' => $locator,
597 'container' => $container,
598 ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
599
c1faf86b 600 // It will stop spinning once the find() method returns false.
d1e55a47 601 $this->spin(
d10ed4d2
AN
602 function() use ($selector, $locator, $container) {
603 if ($container->find($selector, $locator)) {
604 return false;
d1e55a47 605 }
d10ed4d2 606 return true;
d1e55a47 607 },
d10ed4d2
AN
608 // Note: We cannot use $this because the find will then be $this->find(), which leads us to a nested spin().
609 // We cannot nest spins because the outer spin times out before the inner spin completes.
610 [],
05a5d547 611 self::get_extended_timeout(),
d1e55a47
DM
612 $exception,
613 true
614 );
615 }
616
617 /**
618 * Ensures that the provided node is visible and we can interact with it.
619 *
620 * @throws ExpectationException
621 * @param NodeElement $node
622 * @return void Throws an exception if it times out without the element being visible
623 */
624 protected function ensure_node_is_visible($node) {
625
626 if (!$this->running_javascript()) {
627 return;
628 }
629
630 // Exception if it timesout and the element is still there.
c1faf86b 631 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
d1e55a47
DM
632 $exception = new ExpectationException($msg, $this->getSession());
633
c1faf86b 634 // It will stop spinning once the isVisible() method returns true.
d1e55a47
DM
635 $this->spin(
636 function($context, $args) {
637 if ($args->isVisible()) {
638 return true;
639 }
c1faf86b 640 return false;
d1e55a47
DM
641 },
642 $node,
05a5d547 643 self::get_extended_timeout(),
d1e55a47
DM
644 $exception,
645 true
646 );
647 }
648
3df6e801
RT
649 /**
650 * Ensures that the provided node has a attribute value set. This step can be used to check if specific
651 * JS has finished modifying the node.
652 *
653 * @throws ExpectationException
654 * @param NodeElement $node
655 * @param string $attribute attribute name
656 * @param string $attributevalue attribute value to check.
657 * @return void Throws an exception if it times out without the element being visible
658 */
659 protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
660
661 if (!$this->running_javascript()) {
662 return;
663 }
664
665 // Exception if it timesout and the element is still there.
666 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
667 $exception = new ExpectationException($msg, $this->getSession());
668
669 // It will stop spinning once the $args[1]) == $args[2], and method returns true.
670 $this->spin(
671 function($context, $args) {
672 if ($args[0]->getAttribute($args[1]) == $args[2]) {
673 return true;
674 }
675 return false;
676 },
677 array($node, $attribute, $attributevalue),
05a5d547 678 self::get_extended_timeout(),
3df6e801
RT
679 $exception,
680 true
681 );
682 }
683
d1e55a47
DM
684 /**
685 * Ensures that the provided element is visible and we can interact with it.
686 *
687 * Returns the node in case other actions are interested in using it.
688 *
689 * @throws ExpectationException
690 * @param string $element
691 * @param string $selectortype
692 * @return NodeElement Throws an exception if it times out without being visible
693 */
694 protected function ensure_element_is_visible($element, $selectortype) {
695
696 if (!$this->running_javascript()) {
697 return;
698 }
699
700 $node = $this->get_selected_node($selectortype, $element);
701 $this->ensure_node_is_visible($node);
702
703 return $node;
704 }
705
706 /**
707 * Ensures that all the page's editors are loaded.
708 *
9f07f05a 709 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
d1e55a47 710 * @throws ElementNotFoundException
c1faf86b 711 * @throws ExpectationException
d1e55a47
DM
712 * @return void
713 */
714 protected function ensure_editors_are_loaded() {
786ced99
DW
715 global $CFG;
716
717 if (empty($CFG->behat_usedeprecated)) {
718 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
719 }
9f07f05a 720 return;
d1e55a47 721 }
c1faf86b 722
66901a69 723 /**
724 * Checks if the current scenario, or its feature, has a specified tag.
725 *
726 * @param string $tag Tag to check
727 * @return bool True if the tag exists in scenario or feature
728 */
729 public function has_tag(string $tag) : bool {
730 return array_key_exists($tag, behat_hooks::get_tags_for_scenario());
731 }
732
3b0b5e57
RT
733 /**
734 * Change browser window size.
735 * - small: 640x480
736 * - medium: 1024x768
737 * - large: 2560x1600
738 *
739 * @param string $windowsize size of window.
5a14c4d9 740 * @param bool $viewport If true, changes viewport rather than window size
3b0b5e57
RT
741 * @throws ExpectationException
742 */
5a14c4d9 743 protected function resize_window($windowsize, $viewport = false) {
3233f32d
RT
744 // Non JS don't support resize window.
745 if (!$this->running_javascript()) {
746 return;
747 }
748
3b0b5e57
RT
749 switch ($windowsize) {
750 case "small":
3d18e5cf
AN
751 $width = 1024;
752 $height = 768;
3b0b5e57
RT
753 break;
754 case "medium":
3d18e5cf 755 $width = 1366;
3b0b5e57
RT
756 $height = 768;
757 break;
758 case "large":
759 $width = 2560;
760 $height = 1600;
761 break;
762 default:
3233f32d 763 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
3b0b5e57
RT
764 if (empty($matches) || (count($matches) != 2)) {
765 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
766 }
767 $size = explode('x', $windowsize);
768 $width = (int) $size[0];
769 $height = (int) $size[1];
770 }
5a14c4d9 771 if ($viewport) {
772 // When setting viewport size, we set it so that the document width will be exactly
773 // as specified, assuming that there is a vertical scrollbar. (In cases where there is
774 // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
775 // The window inner height will be as specified, which means the available viewport will
776 // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
777 // scrollbars are rare so this doesn't matter.
cd6eadd4
AN
778 $js = <<<EOF
779return (function() {
780 var before = document.body.style.overflowY;
781 document.body.style.overflowY = "scroll";
782 var result = {};
783 result.x = window.outerWidth - document.body.offsetWidth;
784 result.y = window.outerHeight - window.innerHeight;
785 document.body.style.overflowY = before;
786 return result;
787})();
788EOF;
789 $offset = $this->evaluate_script($js);
5a14c4d9 790 $width += $offset['x'];
791 $height += $offset['y'];
792 }
793
3b0b5e57
RT
794 $this->getSession()->getDriver()->resizeWindow($width, $height);
795 }
07298309
RT
796
797 /**
798 * Waits for all the JS to be loaded.
799 *
7bfb575f 800 * @return bool Whether any JS is still pending completion.
07298309
RT
801 */
802 public function wait_for_pending_js() {
07298309 803 if (!$this->running_javascript()) {
7bfb575f
AN
804 // JS is not available therefore there is nothing to wait for.
805 return false;
07298309
RT
806 }
807
7bfb575f
AN
808 return static::wait_for_pending_js_in_session($this->getSession());
809 }
810
811 /**
812 * Waits for all the JS to be loaded.
813 *
814 * @param Session $session The Mink Session where JS can be run
815 * @return bool Whether any JS is still pending completion.
816 */
817 public static function wait_for_pending_js_in_session(Session $session) {
07298309
RT
818 // We don't use behat_base::spin() here as we don't want to end up with an exception
819 // if the page & JSs don't finish loading properly.
05a5d547 820 for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) {
07298309
RT
821 $pending = '';
822 try {
7bfb575f 823 $jscode = trim(preg_replace('/\s+/', ' ', '
5536bf4f 824 return (function() {
d8892dcc
NDM
825 if (document.readyState !== "complete") {
826 return "incomplete";
827 }
828
829 if (typeof M !== "object" || typeof M.util !== "object" || typeof M.util.pending_js === "undefined") {
07298309 830 return "";
07298309 831 }
d8892dcc
NDM
832
833 return M.util.pending_js.join(":");
cd6eadd4
AN
834 })()'));
835 $pending = self::evaluate_script_in_session($session, $jscode);
07298309
RT
836 } catch (NoSuchWindow $nsw) {
837 // We catch an exception here, in case we just closed the window we were interacting with.
838 // No javascript is running if there is no window right?
839 $pending = '';
840 } catch (UnknownError $e) {
841 // M is not defined when the window or the frame don't exist anymore.
842 if (strstr($e->getMessage(), 'M is not defined') != false) {
843 $pending = '';
844 }
845 }
846
847 // If there are no pending JS we stop waiting.
848 if ($pending === '') {
849 return true;
850 }
851
852 // 0.1 seconds.
853 usleep(100000);
854 }
855
7bfb575f 856 // Timeout waiting for JS to complete. It will be caught and forwarded to behat_hooks::i_look_for_exceptions().
05a5d547 857 // It is unlikely that Javascript code of a page or an AJAX request needs more than get_extended_timeout() seconds
07298309
RT
858 // to be loaded, although when pages contains Javascript errors M.util.js_complete() can not be executed, so the
859 // number of JS pending code and JS completed code will not match and we will reach this point.
05a5d547 860 throw new \Exception('Javascript code and/or AJAX requests are not ready after ' .
861 self::get_extended_timeout() .
82ee6f0d
JB
862 ' seconds. There is a Javascript error or the code is extremely slow (' . $pending .
863 '). If you are using a slow machine, consider setting $CFG->behat_increasetimeout.');
07298309 864 }
eb9ca848
RT
865
866 /**
867 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
868 *
869 * Part of behat_hooks class as is part of the testing framework, is auto-executed
870 * after each step so no features will splicitly use it.
871 *
872 * @throws Exception Unknown type, depending on what we caught in the hook or basic \Exception.
873 * @see Moodle\BehatExtension\Tester\MoodleStepTester
874 */
875 public function look_for_exceptions() {
876 // Wrap in try in case we were interacting with a closed window.
877 try {
878
879 // Exceptions.
880 $exceptionsxpath = "//div[@data-rel='fatalerror']";
881 // Debugging messages.
882 $debuggingxpath = "//div[@data-rel='debugging']";
883 // PHP debug messages.
884 $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
885 // Any other backtrace.
886 $othersxpath = "(//*[contains(., ': call to ')])[1]";
887
888 $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
889 $joinedxpath = implode(' | ', $xpaths);
890
891 // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
892 // is faster than to send the 4 xpath queries for each step.
893 if (!$this->getSession()->getDriver()->find($joinedxpath)) {
0c1bcb63
RT
894 // Check if we have recorded any errors in driver process.
895 $phperrors = behat_get_shutdown_process_errors();
896 if (!empty($phperrors)) {
897 foreach ($phperrors as $error) {
898 $errnostring = behat_get_error_string($error['type']);
899 $msgs[] = $errnostring . ": " .$error['message'] . " at " . $error['file'] . ": " . $error['line'];
900 }
901 $msg = "PHP errors found:\n" . implode("\n", $msgs);
902 throw new \Exception(htmlentities($msg));
903 }
904
eb9ca848
RT
905 return;
906 }
907
908 // Exceptions.
909 if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
910
911 // Getting the debugging info and the backtrace.
912 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-error');
63e4df60
DW
913 // If errorinfoboxes is empty, try find alert-danger (bootstrap4) class.
914 if (empty($errorinfoboxes)) {
915 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.alert-danger');
916 }
eb9ca848
RT
917 // If errorinfoboxes is empty, try find notifytiny (original) class.
918 if (empty($errorinfoboxes)) {
919 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
920 }
0c1bcb63
RT
921
922 // If errorinfoboxes is empty, try find ajax/JS exception in dialogue.
923 if (empty($errorinfoboxes)) {
924 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.moodle-exception-message');
925
926 // If ajax/JS exception.
927 if ($errorinfoboxes) {
928 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml());
929 }
930
931 } else {
932 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
933 $this->get_debug_text($errorinfoboxes[1]->getHtml());
934 }
eb9ca848
RT
935
936 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
937 throw new \Exception(html_entity_decode($msg));
938 }
939
940 // Debugging messages.
941 if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
942 $msgs = array();
943 foreach ($debuggingmessages as $debuggingmessage) {
944 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
945 }
946 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
947 throw new \Exception(html_entity_decode($msg));
948 }
949
950 // PHP debug messages.
951 if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
952
953 $msgs = array();
954 foreach ($phpmessages as $phpmessage) {
955 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
956 }
957 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
958 throw new \Exception(html_entity_decode($msg));
959 }
960
961 // Any other backtrace.
962 // First looking through xpath as it is faster than get and parse the whole page contents,
963 // we get the contents and look for matches once we found something to suspect that there is a backtrace.
964 if ($this->getSession()->getDriver()->find($othersxpath)) {
965 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
966 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
967 $msgs = array();
968 foreach ($backtraces[0] as $backtrace) {
969 $msgs[] = $backtrace . '()';
970 }
971 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
972 throw new \Exception(htmlentities($msg));
973 }
974 }
975
976 } catch (NoSuchWindow $e) {
977 // If we were interacting with a popup window it will not exists after closing it.
b095b36c
MN
978 } catch (DriverException $e) {
979 // Same reason as above.
eb9ca848
RT
980 }
981 }
982
8918a811
DM
983 /**
984 * Converts HTML tags to line breaks to display the info in CLI
985 *
986 * @param string $html
987 * @return string
988 */
989 protected function get_debug_text($html) {
990
991 // Replacing HTML tags for new lines and keeping only the text.
992 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
993 return preg_replace("/(\n)+/s", "\n", $notags);
994 }
995
eb9ca848
RT
996 /**
997 * Helper function to execute api in a given context.
998 *
999 * @param string $contextapi context in which api is defined.
1000 * @param array $params list of params to pass.
1001 * @throws Exception
1002 */
1003 protected function execute($contextapi, $params = array()) {
1004 if (!is_array($params)) {
1005 $params = array($params);
1006 }
1007
1008 // Get required context and execute the api.
1009 $contextapi = explode("::", $contextapi);
1010 $context = behat_context_helper::get($contextapi[0]);
1011 call_user_func_array(array($context, $contextapi[1]), $params);
1012
1013 // NOTE: Wait for pending js and look for exception are not optional, as this might lead to unexpected results.
1014 // Don't make them optional for performance reasons.
1015
1016 // Wait for pending js.
1017 $this->wait_for_pending_js();
1018
1019 // Look for exceptions.
1020 $this->look_for_exceptions();
1021 }
353e7876 1022
1023 /**
1024 * Get the actual user in the behat session (note $USER does not correspond to the behat session's user).
1025 * @return mixed
1026 * @throws coding_exception
1027 */
1028 protected function get_session_user() {
1029 global $DB;
1030
1031 $sid = $this->getSession()->getCookie('MoodleSession');
1032 if (empty($sid)) {
1033 throw new coding_exception('failed to get moodle session');
1034 }
1035 $userid = $DB->get_field('sessions', 'userid', ['sid' => $sid]);
1036 if (empty($userid)) {
1037 throw new coding_exception('failed to get user from seession id '.$sid);
1038 }
1039 return $DB->get_record('user', ['id' => $userid]);
1040 }
01f2a530 1041
1042 /**
a1909105 1043 * Set current $USER, reset access cache.
9b1fc262
SL
1044 *
1045 * In some cases, behat will execute the code as admin but in many cases we need to set an specific user as some
1046 * API's might rely on the logged user to take some action.
1047 *
a1909105 1048 * @param null|int|stdClass $user user record, null or 0 means non-logged-in, positive integer means userid
a1909105
SL
1049 */
1050 public static function set_user($user = null) {
1051 global $DB;
1052
1053 if (is_object($user)) {
1054 $user = clone($user);
1055 } else if (!$user) {
1056 // Assign valid data to admin user (some generator-related code needs a valid user).
1057 $user = $DB->get_record('user', array('username' => 'admin'));
1058 } else {
9b1fc262 1059 $user = $DB->get_record('user', array('id' => $user));
a1909105
SL
1060 }
1061 unset($user->description);
1062 unset($user->access);
1063 unset($user->preference);
1064
9b1fc262 1065 // Ensure session is empty, as it may contain caches and user specific info.
a1909105
SL
1066 \core\session\manager::init_empty_session();
1067
1068 \core\session\manager::set_user($user);
1069 }
1070 /**
01f2a530 1071 * Trigger click on node via javascript instead of actually clicking on it via pointer.
1072 *
1073 * This function resolves the issue of nested elements with click listeners or links - in these cases clicking via
1074 * the pointer may accidentally cause a click on the wrong element.
1075 * Example of issue: clicking to expand navigation nodes when the config value linkadmincategories is enabled.
1076 * @param NodeElement $node
1077 */
1078 protected function js_trigger_click($node) {
1079 if (!$this->running_javascript()) {
1080 $node->click();
1081 }
1082 $this->ensure_node_is_visible($node); // Ensures hidden elements can't be clicked.
1083 $xpath = $node->getXpath();
b5be3875
MN
1084 $driver = $this->getSession()->getDriver();
1085 if ($driver instanceof \Moodle\BehatExtension\Driver\MoodleSelenium2Driver) {
1086 $script = "Syn.click({{ELEMENT}})";
1087 $driver->triggerSynScript($xpath, $script);
1088 } else {
1089 $driver->click($xpath);
1090 }
01f2a530 1091 }
05a5d547 1092
4024556b
TH
1093 /**
1094 * Convert page names to URLs for steps like 'When I am on the "[page name]" page'.
1095 *
1096 * You should override this as appropriate for your plugin. The method
1097 * {@link behat_navigation::resolve_core_page_url()} is a good example.
1098 *
1099 * Your overridden method should document the recognised page types with
1100 * a table like this:
1101 *
1102 * Recognised page names are:
1103 * | Page | Description |
1104 *
1105 * @param string $page name of the page, with the component name removed e.g. 'Admin notification'.
1106 * @return moodle_url the corresponding URL.
1107 * @throws Exception with a meaningful error message if the specified page cannot be found.
1108 */
1109 protected function resolve_page_url(string $page): moodle_url {
1110 throw new Exception('Component "' . get_class($this) .
1111 '" does not support the generic \'When I am on the "' . $page .
1112 '" page\' navigation step.');
1113 }
1114
1115 /**
1116 * Convert page names to URLs for steps like 'When I am on the "[identifier]" "[page type]" page'.
1117 *
1118 * A typical example might be:
1119 * When I am on the "Test quiz" "mod_quiz > Responses report" page
1120 * which would cause this method in behat_mod_quiz to be called with
1121 * arguments 'Responses report', 'Test quiz'.
1122 *
1123 * You should override this as appropriate for your plugin. The method
1124 * {@link behat_navigation::resolve_core_page_instance_url()} is a good example.
1125 *
1126 * Your overridden method should document the recognised page types with
1127 * a table like this:
1128 *
1129 * Recognised page names are:
1130 * | Type | identifier meaning | Description |
1131 *
1132 * @param string $type identifies which type of page this is, e.g. 'Attempt review'.
1133 * @param string $identifier identifies the particular page, e.g. 'Test quiz > student > Attempt 1'.
1134 * @return moodle_url the corresponding URL.
1135 * @throws Exception with a meaningful error message if the specified page cannot be found.
1136 */
1137 protected function resolve_page_instance_url(string $type, string $identifier): moodle_url {
1138 throw new Exception('Component "' . get_class($this) .
1139 '" does not support the generic \'When I am on the "' . $identifier .
1140 '" "' . $type . '" page\' navigation step.');
1141 }
1142
05a5d547 1143 /**
1144 * Gets the required timeout in seconds.
1145 *
1146 * @param int $timeout One of the TIMEOUT constants
1147 * @return int Actual timeout (in seconds)
1148 */
1149 protected static function get_real_timeout(int $timeout) : int {
1150 global $CFG;
1151 if (!empty($CFG->behat_increasetimeout)) {
1152 return $timeout * $CFG->behat_increasetimeout;
1153 } else {
1154 return $timeout;
1155 }
1156 }
1157
1158 /**
1159 * Gets the default timeout.
1160 *
1161 * The timeout for each Behat step (load page, wait for an element to load...).
1162 *
1163 * @return int Timeout in seconds
1164 */
1165 public static function get_timeout() : int {
1166 return self::get_real_timeout(6);
1167 }
1168
1169 /**
1170 * Gets the reduced timeout.
1171 *
1172 * A reduced timeout for cases where self::get_timeout() is too much
1173 * and a simple $this->getSession()->getPage()->find() could not
1174 * be enough.
1175 *
1176 * @return int Timeout in seconds
1177 */
1178 public static function get_reduced_timeout() : int {
1179 return self::get_real_timeout(2);
1180 }
1181
1182 /**
1183 * Gets the extended timeout.
1184 *
1185 * A longer timeout for cases where the normal timeout is not enough.
1186 *
1187 * @return int Timeout in seconds
1188 */
1189 public static function get_extended_timeout() : int {
1190 return self::get_real_timeout(10);
1191 }
61832fae
AN
1192
1193 /**
1194 * Return a list of the exact named selectors for the component.
1195 *
33da028c
TH
1196 * Named selectors are what make Behat steps like
1197 * Then I should see "Useful text" in the "General" "fieldset"
1198 * work. Here, "fieldset" is the named selector, and "General" is the locator.
1199 *
1200 * If you override this method in your plugin (e.g. mod_mymod), to define
1201 * new selectors specific to your plugin. For example, if you returned
1202 * new behat_component_named_selector('Thingy',
1203 * [".//some/xpath//img[contains(@alt, %locator%)]/.."])
1204 * then
1205 * Then I should see "Useful text" in the "Whatever" "mod_mymod > Thingy"
1206 * would work.
1207 *
1208 * This method should return a list of {@link behat_component_named_selector} and
1209 * the docs on that class explain how it works.
1210 *
61832fae
AN
1211 * @return behat_component_named_selector[]
1212 */
1213 public static function get_exact_named_selectors(): array {
1214 return [];
1215 }
1216
1217 /**
1218 * Return a list of the partial named selectors for the component.
1219 *
33da028c
TH
1220 * Like the exact named selectors above, but the locator only
1221 * needs to match part of the text. For example, the standard
1222 * "button" is a partial selector, so:
1223 * When I click "Save" "button"
1224 * will activate "Save changes".
1225 *
61832fae
AN
1226 * @return behat_component_named_selector[]
1227 */
1228 public static function get_partial_named_selectors(): array {
1229 return [];
1230 }
1231
1232 /**
33da028c
TH
1233 * Return a list of the Mink named replacements for the component.
1234 *
1235 * Named replacements allow you to define parts of an xpath that can be reused multiple times, or in multiple
1236 * xpaths.
1237 *
1238 * This method should return a list of {@link behat_component_named_replacement} and the docs on that class explain
1239 * how it works.
61832fae
AN
1240 *
1241 * @return behat_component_named_replacement[]
1242 */
1243 public static function get_named_replacements(): array {
1244 return [];
1245 }
6d5d1935
AN
1246
1247 /**
1248 * Evaluate the supplied script in the current session, returning the result.
1249 *
1250 * @param string $script
1251 * @return mixed
1252 */
1253 public function evaluate_script(string $script) {
1254 return self::evaluate_script_in_session($this->getSession(), $script);
1255 }
1256
1257 /**
1258 * Evaluate the supplied script in the specified session, returning the result.
1259 *
1260 * @param Session $session
1261 * @param string $script
1262 * @return mixed
1263 */
1264 public static function evaluate_script_in_session(Session $session, string $script) {
1265 self::require_javascript_in_session($session);
1266
1267 return $session->evaluateScript($script);
1268 }
1269
1270 /**
1271 * Execute the supplied script in the current session.
1272 *
1273 * No result will be returned.
1274 *
1275 * @param string $script
1276 */
1277 public function execute_script(string $script): void {
1278 self::execute_script_in_session($this->getSession(), $script);
1279 }
1280
1281 /**
1282 * Excecute the supplied script in the specified session.
1283 *
1284 * No result will be returned.
1285 *
1286 * @param Session $session
1287 * @param string $script
1288 */
1289 public static function execute_script_in_session(Session $session, string $script): void {
1290 self::require_javascript_in_session($session);
1291
1292 $session->executeScript($script);
1293 }
083604ea
AN
1294
1295 /**
1296 * Get the session key for the current session via Javascript.
1297 *
1298 * @return string
1299 */
1300 public function get_sesskey(): string {
1301 $script = <<<EOF
1302return (function() {
1303if (M && M.cfg && M.cfg.sesskey) {
1304 return M.cfg.sesskey;
1305}
1306return '';
1307})()
1308EOF;
1309
1310 return $this->evaluate_script($script);
1311 }
d4322e38 1312}