weekly release 3.10dev
[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
69 * @todo MDL-64982 This will be deleted in Moodle 4.1
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
78 * @todo MDL-64982 This will be deleted in Moodle 4.1
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
87 * @todo MDL-64982 This will be deleted in Moodle 4.1
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.
94 */
41f4dabe 95 const PAGE_READY_JS = '(typeof M !== "undefined" && M.util && M.util.pending_js && !Boolean(M.util.pending_js.length)) && (document.readyState === "complete")';
d4322e38 96
786ea937
DM
97 /**
98 * Locates url, based on provided path.
99 * Override to provide custom routing mechanism.
100 *
101 * @see Behat\MinkExtension\Context\MinkContext
102 * @param string $path
103 * @return string
104 */
40923977 105 protected function locate_path($path) {
46ac40cd
DM
106 $starturl = rtrim($this->getMinkParameter('base_url'), '/') . '/';
107 return 0 !== strpos($path, 'http') ? $starturl . ltrim($path, '/') : $path;
786ea937
DM
108 }
109
ff48a235 110 /**
f8f1bdc3 111 * Returns the first matching element.
ff48a235
DM
112 *
113 * @link http://mink.behat.org/#traverse-the-page-selectors
ff48a235
DM
114 * @param string $selector The selector type (css, xpath, named...)
115 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
40923977 116 * @param Exception $exception Otherwise we throw exception with generic info
072f67fc 117 * @param NodeElement $node Spins around certain DOM node instead of the whole page
74c78e74 118 * @param int $timeout Forces a specific time out (in seconds).
ff48a235
DM
119 * @return NodeElement
120 */
74c78e74 121 protected function find($selector, $locator, $exception = false, $node = false, $timeout = false) {
34503872
AN
122 if ($selector === 'NodeElement' && is_a($locator, NodeElement::class)) {
123 // Support a NodeElement being passed in for use in step chaining.
124 return $locator;
125 }
126
f8f1bdc3 127 // Returns the first match.
74c78e74 128 $items = $this->find_all($selector, $locator, $exception, $node, $timeout);
f8f1bdc3
DM
129 return count($items) ? reset($items) : null;
130 }
131
132 /**
133 * Returns all matching elements.
134 *
135 * Adapter to Behat\Mink\Element\Element::findAll() using the spin() method.
136 *
137 * @link http://mink.behat.org/#traverse-the-page-selectors
138 * @param string $selector The selector type (css, xpath, named...)
139 * @param mixed $locator It depends on the $selector, can be the xpath, a name, a css locator...
140 * @param Exception $exception Otherwise we throw expcetion with generic info
700682dc 141 * @param NodeElement $container Restrict the search to just children of the specified container
74c78e74 142 * @param int $timeout Forces a specific time out (in seconds). If 0 is provided the default timeout will be applied.
f8f1bdc3
DM
143 * @return array NodeElements list
144 */
700682dc 145 protected function find_all($selector, $locator, $exception = false, $container = false, $timeout = false) {
42ad096f
RT
146 // Throw exception, so dev knows it is not supported.
147 if ($selector === 'named') {
148 $exception = 'Using the "named" selector is deprecated as of 3.1. '
149 .' Use the "named_partial" or use the "named_exact" selector instead.';
150 throw new ExpectationException($exception, $this->getSession());
151 }
152
ff48a235
DM
153 // Generic info.
154 if (!$exception) {
ff48a235 155 // With named selectors we can be more specific.
07298309 156 if (($selector == 'named_exact') || ($selector == 'named_partial')) {
ff48a235
DM
157 $exceptiontype = $locator[0];
158 $exceptionlocator = $locator[1];
0a7f6a02
DM
159
160 // If we are in a @javascript session all contents would be displayed as HTML characters.
eff79d53 161 if ($this->running_javascript()) {
0a7f6a02
DM
162 $locator[1] = html_entity_decode($locator[1], ENT_NOQUOTES);
163 }
164
ff48a235
DM
165 } else {
166 $exceptiontype = $selector;
167 $exceptionlocator = $locator;
168 }
169
170 $exception = new ElementNotFoundException($this->getSession(), $exceptiontype, null, $exceptionlocator);
171 }
172
74c78e74
DM
173 // How much we will be waiting for the element to appear.
174 if (!$timeout) {
05a5d547 175 $timeout = self::get_timeout();
74c78e74
DM
176 $microsleep = false;
177 } else {
178 // Spinning each 0.1 seconds if the timeout was forced as we understand
179 // that is a special case and is good to refine the performance as much
180 // as possible.
181 $microsleep = true;
182 }
183
700682dc
AN
184 // Normalise the values in order to perform the search.
185 [
186 'selector' => $selector,
187 'locator' => $locator,
188 'container' => $container,
189 ] = $this->normalise_selector($selector, $locator, $container ?: $this->getSession()->getPage());
190
ff48a235
DM
191 // Waits for the node to appear if it exists, otherwise will timeout and throw the provided exception.
192 return $this->spin(
700682dc
AN
193 function() use ($selector, $locator, $container) {
194 return $container->findAll($selector, $locator);
195 }, [], $timeout, $exception, $microsleep
196 );
197 }
072f67fc 198
700682dc
AN
199 /**
200 * Normalise the locator and selector.
201 *
202 * @param string $selector The type of thing to search
203 * @param mixed $locator The locator value. Can be an array, but is more likely a string.
204 * @param Element $container An optional container to search within
205 * @return array The selector, locator, and container to search within
206 */
207 public function normalise_selector(string $selector, $locator, Element $container): array {
b983ae4a
AN
208 // Check for specific transformations for this selector type.
209 $transformfunction = "transform_find_for_{$selector}";
210 if (method_exists('behat_selectors', $transformfunction)) {
211 // A selector-specific transformation exists.
212 // Perform initial transformation of the selector within the current container.
213 [
214 'selector' => $selector,
215 'locator' => $locator,
216 'container' => $container,
217 ] = behat_selectors::{$transformfunction}($this, $locator, $container);
218 }
219
700682dc
AN
220 // Normalise the css and xpath selector types.
221 if ('css_element' === $selector) {
222 $selector = 'css';
223 } else if ('xpath_element' === $selector) {
224 $selector = 'xpath';
225 }
072f67fc 226
61832fae 227 // Convert to a named selector where the selector type is not a known selector.
700682dc
AN
228 $converttonamed = !$this->getSession()->getSelectorsHandler()->isSelectorRegistered($selector);
229 $converttonamed = $converttonamed && 'xpath' !== $selector;
230 if ($converttonamed) {
61832fae
AN
231 if (behat_partial_named_selector::is_deprecated_selector($selector)) {
232 if ($replacement = behat_partial_named_selector::get_deprecated_replacement($selector)) {
233 error_log("The '{$selector}' selector has been replaced with {$replacement}");
234 $selector = $replacement;
235 }
236 } else if (behat_exact_named_selector::is_deprecated_selector($selector)) {
237 if ($replacement = behat_exact_named_selector::get_deprecated_replacement($selector)) {
238 error_log("The '{$selector}' selector has been replaced with {$replacement}");
239 $selector = $replacement;
240 }
241 }
242
700682dc
AN
243 $allowedpartialselectors = behat_partial_named_selector::get_allowed_selectors();
244 $allowedexactselectors = behat_exact_named_selector::get_allowed_selectors();
245 if (isset($allowedpartialselectors[$selector])) {
246 $locator = behat_selectors::normalise_named_selector($allowedpartialselectors[$selector], $locator);
247 $selector = 'named_partial';
248 } else if (isset($allowedexactselectors[$selector])) {
249 $locator = behat_selectors::normalise_named_selector($allowedexactselectors[$selector], $locator);
250 $selector = 'named_exact';
251 } else {
61832fae 252 throw new ExpectationException("The '{$selector}' selector type is not registered.", $this->getSession()->getDriver());
700682dc
AN
253 }
254 }
255
256 return [
257 'selector' => $selector,
258 'locator' => $locator,
259 'container' => $container,
260 ];
ff48a235
DM
261 }
262
263 /**
264 * Finds DOM nodes in the page using named selectors.
265 *
266 * The point of using this method instead of Mink ones is the spin
267 * method of behat_base::find() that looks for the element until it
268 * is available or it timeouts, this avoids the false failures received
269 * when selenium tries to execute commands on elements that are not
270 * ready to be used.
271 *
272 * All steps that requires elements to be available before interact with
273 * them should use one of the find* methods.
274 *
275 * The methods calls requires a {'find_' . $elementtype}($locator)
276 * format, like find_link($locator), find_select($locator),
277 * find_button($locator)...
278 *
279 * @link http://mink.behat.org/#named-selectors
280 * @throws coding_exception
46ac40cd 281 * @param string $name The name of the called method
ff48a235
DM
282 * @param mixed $arguments
283 * @return NodeElement
284 */
285 public function __call($name, $arguments) {
700682dc
AN
286 if (substr($name, 0, 5) === 'find_') {
287 return call_user_func_array([$this, 'find'], array_merge(
288 [substr($name, 5)],
289 $arguments
290 ));
ff48a235
DM
291 }
292
700682dc 293 throw new coding_exception("The '{$name}' method does not exist");
ff48a235
DM
294 }
295
49d91129
DM
296 /**
297 * Escapes the double quote character.
298 *
299 * Double quote is the argument delimiter, it can be escaped
300 * with a backslash, but we auto-remove this backslashes
301 * before the step execution, this method is useful when using
302 * arguments as arguments for other steps.
303 *
304 * @param string $string
305 * @return string
306 */
307 public function escape($string) {
308 return str_replace('"', '\"', $string);
309 }
310
786ea937
DM
311 /**
312 * Executes the passed closure until returns true or time outs.
313 *
314 * In most cases the document.readyState === 'complete' will be enough, but sometimes JS
315 * requires more time to be completely loaded or an element to be visible or whatever is required to
316 * perform some action on an element; this method receives a closure which should contain the
317 * required statements to ensure the step definition actions and assertions have all their needs
318 * satisfied and executes it until they are satisfied or it timeouts. Redirects the return of the
319 * closure to the caller.
320 *
321 * The closures requirements to work well with this spin method are:
322 * - Must return false, null or '' if something goes wrong
323 * - Must return something != false if finishes as expected, this will be the (mixed) value
324 * returned by spin()
325 *
ff48a235 326 * The arguments of the closure are mixed, use $args depending on your needs.
786ea937 327 *
ff48a235 328 * You can provide an exception to give more accurate feedback to tests writers, otherwise the
c51c3b55 329 * closure exception will be used, but you must provide an exception if the closure does not throw
ff48a235
DM
330 * an exception.
331 *
8e5f86bc
SH
332 * @throws Exception If it timeouts without receiving something != false from the closure
333 * @param Function|array|string $lambda The function to execute or an array passed to call_user_func (maps to a class method)
334 * @param mixed $args Arguments to pass to the closure
335 * @param int $timeout Timeout in seconds
336 * @param Exception $exception The exception to throw in case it time outs.
337 * @param bool $microsleep If set to true it'll sleep micro seconds rather than seconds.
786ea937
DM
338 * @return mixed The value returned by the closure
339 */
8e5f86bc 340 protected function spin($lambda, $args = false, $timeout = false, $exception = false, $microsleep = false) {
786ea937
DM
341
342 // Using default timeout which is pretty high.
343 if (!$timeout) {
05a5d547 344 $timeout = self::get_timeout();
786ea937
DM
345 }
346
c7807a10
AN
347 $start = microtime(true);
348 $end = $start + $timeout;
80ac8522 349
c7807a10 350 do {
786ea937
DM
351 // We catch the exception thrown by the step definition to execute it again.
352 try {
786ea937 353 // We don't check with !== because most of the time closures will return
ff48a235
DM
354 // direct Behat methods returns and we are not sure it will be always (bool)false
355 // if it just runs the behat method without returning anything $return == null.
8e5f86bc 356 if ($return = call_user_func($lambda, $this, $args)) {
786ea937
DM
357 return $return;
358 }
46ac40cd 359 } catch (Exception $e) {
ff48a235
DM
360 // We would use the first closure exception if no exception has been provided.
361 if (!$exception) {
362 $exception = $e;
363 }
786ea937
DM
364 }
365
c7807a10
AN
366 if (!$this->running_javascript()) {
367 break;
8e5f86bc 368 }
c7807a10
AN
369
370 usleep(100000);
371
372 } while (microtime(true) < $end);
786ea937 373
ff48a235
DM
374 // Using coding_exception as is a development issue if no exception has been provided.
375 if (!$exception) {
8e5f86bc 376 $exception = new coding_exception('spin method requires an exception if the callback does not throw an exception');
ff48a235
DM
377 }
378
786ea937
DM
379 // Throwing exception to the user.
380 throw $exception;
381 }
382
40923977
DM
383 /**
384 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
385 *
072f67fc
DM
386 * Use behat_base::get_text_selector_node() for text-based selectors.
387 *
40923977
DM
388 * @throws ElementNotFoundException Thrown by behat_base::find
389 * @param string $selectortype
390 * @param string $element
391 * @return NodeElement
392 */
393 protected function get_selected_node($selectortype, $element) {
d10ed4d2 394 return $this->find($selectortype, $element);
40923977
DM
395 }
396
072f67fc
DM
397 /**
398 * Gets a NodeElement based on the locator and selector type received as argument from steps definitions.
399 *
400 * @throws ElementNotFoundException Thrown by behat_base::find
401 * @param string $selectortype
402 * @param string $element
403 * @return NodeElement
404 */
405 protected function get_text_selector_node($selectortype, $element) {
072f67fc
DM
406 // Getting Mink selector and locator.
407 list($selector, $locator) = $this->transform_text_selector($selectortype, $element);
408
409 // Returns the NodeElement.
410 return $this->find($selector, $locator);
411 }
412
413 /**
414 * Gets the requested element inside the specified container.
415 *
416 * @throws ElementNotFoundException Thrown by behat_base::find
417 * @param mixed $selectortype The element selector type.
418 * @param mixed $element The element locator.
419 * @param mixed $containerselectortype The container selector type.
420 * @param mixed $containerelement The container locator.
421 * @return NodeElement
422 */
423 protected function get_node_in_container($selectortype, $element, $containerselectortype, $containerelement) {
072f67fc
DM
424 // Gets the container, it will always be text based.
425 $containernode = $this->get_text_selector_node($containerselectortype, $containerelement);
426
072f67fc
DM
427 $locatorexceptionmsg = $element . '" in the "' . $containerelement. '" "' . $containerselectortype. '"';
428 $exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);
429
d10ed4d2 430 return $this->find($selectortype, $element, $exception, $containernode);
072f67fc
DM
431 }
432
40923977
DM
433 /**
434 * Transforms from step definition's argument style to Mink format.
435 *
436 * Mink has 3 different selectors css, xpath and named, where named
437 * selectors includes link, button, field... to simplify and group multiple
438 * steps in one we use the same interface, considering all link, buttons...
439 * at the same level as css selectors and xpath; this method makes the
440 * conversion from the arguments received by the steps to the selectors and locators
441 * required to interact with Mink.
442 *
443 * @throws ExpectationException
444 * @param string $selectortype It can be css, xpath or any of the named selectors.
445 * @param string $element The locator (or string) we are looking for.
446 * @return array Contains the selector and the locator expected by Mink.
447 */
448 protected function transform_selector($selectortype, $element) {
17344d4c
DM
449 // Here we don't know if an allowed text selector is being used.
450 $selectors = behat_selectors::get_allowed_selectors();
451 if (!isset($selectors[$selectortype])) {
40923977
DM
452 throw new ExpectationException('The "' . $selectortype . '" selector type does not exist', $this->getSession());
453 }
454
700682dc
AN
455 [
456 'selector' => $selector,
457 'locator' => $locator,
458 ] = $this->normalise_selector($selectortype, $element, $this->getSession()->getPage());
459
460 return [$selector, $locator];
40923977
DM
461 }
462
072f67fc
DM
463 /**
464 * Transforms from step definition's argument style to Mink format.
465 *
466 * Delegates all the process to behat_base::transform_selector() checking
467 * the provided $selectortype.
468 *
469 * @throws ExpectationException
470 * @param string $selectortype It can be css, xpath or any of the named selectors.
471 * @param string $element The locator (or string) we are looking for.
472 * @return array Contains the selector and the locator expected by Mink.
473 */
474 protected function transform_text_selector($selectortype, $element) {
475
17344d4c
DM
476 $selectors = behat_selectors::get_allowed_text_selectors();
477 if (empty($selectors[$selectortype])) {
072f67fc
DM
478 throw new ExpectationException('The "' . $selectortype . '" selector can not be used to select text nodes', $this->getSession());
479 }
480
481 return $this->transform_selector($selectortype, $element);
482 }
483
eff79d53 484 /**
6d5d1935 485 * Whether Javascript is available in the current Session.
eff79d53
DM
486 *
487 * @return boolean
488 */
489 protected function running_javascript() {
6d5d1935
AN
490 return self::running_javascript_in_session($this->getSession());
491 }
492
493 /**
494 * Require that javascript be available in the current Session.
495 *
496 * @throws DriverException
497 */
498 protected function require_javascript() {
499 return self::require_javascript_in_session($this->getSession());
500 }
501
502 /**
503 * Whether Javascript is available in the specified Session.
504 *
505 * @param Session $session
506 * @return boolean
507 */
508 protected static function running_javascript_in_session(Session $session): bool {
509 return get_class($session->getDriver()) !== 'Behat\Mink\Driver\GoutteDriver';
510 }
511
512 /**
513 * Require that javascript be available for the specified Session.
514 *
515 * @param Session $session
516 * @throws DriverException
517 */
518 protected static function require_javascript_in_session(Session $session): void {
519 if (self::running_javascript_in_session($session)) {
520 return;
521 }
522
523 throw new DriverException('Javascript is required');
eff79d53
DM
524 }
525
079eae37 526 /**
527 * Checks if the current page is part of the mobile app.
528 *
529 * @return bool True if it's in the app
530 */
531 protected function is_in_app() : bool {
532 // Cannot be in the app if there's no @app tag on scenario.
533 if (!$this->has_tag('app')) {
534 return false;
535 }
536
537 // Check on page to see if it's an app page. Safest way is to look for added JavaScript.
cd6eadd4 538 return $this->evaluate_script('return typeof window.behat') === 'object';
079eae37 539 }
540
d1e55a47
DM
541 /**
542 * Spins around an element until it exists
543 *
544 * @throws ExpectationException
d10ed4d2 545 * @param string $locator
d1e55a47
DM
546 * @param string $selectortype
547 * @return void
548 */
d10ed4d2 549 protected function ensure_element_exists($locator, $selectortype) {
d1e55a47 550 // Exception if it timesout and the element is still there.
d10ed4d2 551 $msg = "The '{$locator}' element does not exist and should";
d1e55a47
DM
552 $exception = new ExpectationException($msg, $this->getSession());
553
d10ed4d2
AN
554 // Normalise the values in order to perform the search.
555 [
556 'selector' => $selector,
557 'locator' => $locator,
558 'container' => $container,
559 ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
560
c1faf86b 561 // It will stop spinning once the find() method returns true.
d1e55a47 562 $this->spin(
d10ed4d2
AN
563 function() use ($selector, $locator, $container) {
564 if ($container->find($selector, $locator)) {
d1e55a47
DM
565 return true;
566 }
c1faf86b 567 return false;
d1e55a47 568 },
d10ed4d2 569 [],
05a5d547 570 self::get_extended_timeout(),
d1e55a47
DM
571 $exception,
572 true
573 );
d1e55a47
DM
574 }
575
576 /**
577 * Spins until the element does not exist
578 *
579 * @throws ExpectationException
d10ed4d2 580 * @param string $locator
d1e55a47
DM
581 * @param string $selectortype
582 * @return void
583 */
d10ed4d2 584 protected function ensure_element_does_not_exist($locator, $selectortype) {
d1e55a47 585 // Exception if it timesout and the element is still there.
d10ed4d2 586 $msg = "The '{$locator}' element exists and should not exist";
d1e55a47
DM
587 $exception = new ExpectationException($msg, $this->getSession());
588
d10ed4d2
AN
589 // Normalise the values in order to perform the search.
590 [
591 'selector' => $selector,
592 'locator' => $locator,
593 'container' => $container,
594 ] = $this->normalise_selector($selectortype, $locator, $this->getSession()->getPage());
595
c1faf86b 596 // It will stop spinning once the find() method returns false.
d1e55a47 597 $this->spin(
d10ed4d2
AN
598 function() use ($selector, $locator, $container) {
599 if ($container->find($selector, $locator)) {
600 return false;
d1e55a47 601 }
d10ed4d2 602 return true;
d1e55a47 603 },
d10ed4d2
AN
604 // Note: We cannot use $this because the find will then be $this->find(), which leads us to a nested spin().
605 // We cannot nest spins because the outer spin times out before the inner spin completes.
606 [],
05a5d547 607 self::get_extended_timeout(),
d1e55a47
DM
608 $exception,
609 true
610 );
611 }
612
613 /**
614 * Ensures that the provided node is visible and we can interact with it.
615 *
616 * @throws ExpectationException
617 * @param NodeElement $node
618 * @return void Throws an exception if it times out without the element being visible
619 */
620 protected function ensure_node_is_visible($node) {
621
622 if (!$this->running_javascript()) {
623 return;
624 }
625
626 // Exception if it timesout and the element is still there.
c1faf86b 627 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
d1e55a47
DM
628 $exception = new ExpectationException($msg, $this->getSession());
629
c1faf86b 630 // It will stop spinning once the isVisible() method returns true.
d1e55a47
DM
631 $this->spin(
632 function($context, $args) {
633 if ($args->isVisible()) {
634 return true;
635 }
c1faf86b 636 return false;
d1e55a47
DM
637 },
638 $node,
05a5d547 639 self::get_extended_timeout(),
d1e55a47
DM
640 $exception,
641 true
642 );
643 }
644
3df6e801
RT
645 /**
646 * Ensures that the provided node has a attribute value set. This step can be used to check if specific
647 * JS has finished modifying the node.
648 *
649 * @throws ExpectationException
650 * @param NodeElement $node
651 * @param string $attribute attribute name
652 * @param string $attributevalue attribute value to check.
653 * @return void Throws an exception if it times out without the element being visible
654 */
655 protected function ensure_node_attribute_is_set($node, $attribute, $attributevalue) {
656
657 if (!$this->running_javascript()) {
658 return;
659 }
660
661 // Exception if it timesout and the element is still there.
662 $msg = 'The "' . $node->getXPath() . '" xpath node is not visible and it should be visible';
663 $exception = new ExpectationException($msg, $this->getSession());
664
665 // It will stop spinning once the $args[1]) == $args[2], and method returns true.
666 $this->spin(
667 function($context, $args) {
668 if ($args[0]->getAttribute($args[1]) == $args[2]) {
669 return true;
670 }
671 return false;
672 },
673 array($node, $attribute, $attributevalue),
05a5d547 674 self::get_extended_timeout(),
3df6e801
RT
675 $exception,
676 true
677 );
678 }
679
d1e55a47
DM
680 /**
681 * Ensures that the provided element is visible and we can interact with it.
682 *
683 * Returns the node in case other actions are interested in using it.
684 *
685 * @throws ExpectationException
686 * @param string $element
687 * @param string $selectortype
688 * @return NodeElement Throws an exception if it times out without being visible
689 */
690 protected function ensure_element_is_visible($element, $selectortype) {
691
692 if (!$this->running_javascript()) {
693 return;
694 }
695
696 $node = $this->get_selected_node($selectortype, $element);
697 $this->ensure_node_is_visible($node);
698
699 return $node;
700 }
701
702 /**
703 * Ensures that all the page's editors are loaded.
704 *
9f07f05a 705 * @deprecated since Moodle 2.7 MDL-44084 - please do not use this function any more.
d1e55a47 706 * @throws ElementNotFoundException
c1faf86b 707 * @throws ExpectationException
d1e55a47
DM
708 * @return void
709 */
710 protected function ensure_editors_are_loaded() {
786ced99
DW
711 global $CFG;
712
713 if (empty($CFG->behat_usedeprecated)) {
714 debugging('Function behat_base::ensure_editors_are_loaded() is deprecated. It is no longer required.');
715 }
9f07f05a 716 return;
d1e55a47 717 }
c1faf86b 718
66901a69 719 /**
720 * Checks if the current scenario, or its feature, has a specified tag.
721 *
722 * @param string $tag Tag to check
723 * @return bool True if the tag exists in scenario or feature
724 */
725 public function has_tag(string $tag) : bool {
726 return array_key_exists($tag, behat_hooks::get_tags_for_scenario());
727 }
728
3b0b5e57
RT
729 /**
730 * Change browser window size.
731 * - small: 640x480
732 * - medium: 1024x768
733 * - large: 2560x1600
734 *
735 * @param string $windowsize size of window.
5a14c4d9 736 * @param bool $viewport If true, changes viewport rather than window size
3b0b5e57
RT
737 * @throws ExpectationException
738 */
5a14c4d9 739 protected function resize_window($windowsize, $viewport = false) {
3233f32d
RT
740 // Non JS don't support resize window.
741 if (!$this->running_javascript()) {
742 return;
743 }
744
3b0b5e57
RT
745 switch ($windowsize) {
746 case "small":
3d18e5cf
AN
747 $width = 1024;
748 $height = 768;
3b0b5e57
RT
749 break;
750 case "medium":
3d18e5cf 751 $width = 1366;
3b0b5e57
RT
752 $height = 768;
753 break;
754 case "large":
755 $width = 2560;
756 $height = 1600;
757 break;
758 default:
3233f32d 759 preg_match('/^(\d+x\d+)$/', $windowsize, $matches);
3b0b5e57
RT
760 if (empty($matches) || (count($matches) != 2)) {
761 throw new ExpectationException("Invalid screen size, can't resize", $this->getSession());
762 }
763 $size = explode('x', $windowsize);
764 $width = (int) $size[0];
765 $height = (int) $size[1];
766 }
5a14c4d9 767 if ($viewport) {
768 // When setting viewport size, we set it so that the document width will be exactly
769 // as specified, assuming that there is a vertical scrollbar. (In cases where there is
770 // no scrollbar it will be slightly wider. We presume this is rare and predictable.)
771 // The window inner height will be as specified, which means the available viewport will
772 // actually be smaller if there is a horizontal scrollbar. We assume that horizontal
773 // scrollbars are rare so this doesn't matter.
cd6eadd4
AN
774 $js = <<<EOF
775return (function() {
776 var before = document.body.style.overflowY;
777 document.body.style.overflowY = "scroll";
778 var result = {};
779 result.x = window.outerWidth - document.body.offsetWidth;
780 result.y = window.outerHeight - window.innerHeight;
781 document.body.style.overflowY = before;
782 return result;
783})();
784EOF;
785 $offset = $this->evaluate_script($js);
5a14c4d9 786 $width += $offset['x'];
787 $height += $offset['y'];
788 }
789
3b0b5e57
RT
790 $this->getSession()->getDriver()->resizeWindow($width, $height);
791 }
07298309
RT
792
793 /**
794 * Waits for all the JS to be loaded.
795 *
7bfb575f 796 * @return bool Whether any JS is still pending completion.
07298309
RT
797 */
798 public function wait_for_pending_js() {
07298309 799 if (!$this->running_javascript()) {
7bfb575f
AN
800 // JS is not available therefore there is nothing to wait for.
801 return false;
07298309
RT
802 }
803
7bfb575f
AN
804 return static::wait_for_pending_js_in_session($this->getSession());
805 }
806
807 /**
808 * Waits for all the JS to be loaded.
809 *
810 * @param Session $session The Mink Session where JS can be run
811 * @return bool Whether any JS is still pending completion.
812 */
813 public static function wait_for_pending_js_in_session(Session $session) {
07298309
RT
814 // We don't use behat_base::spin() here as we don't want to end up with an exception
815 // if the page & JSs don't finish loading properly.
05a5d547 816 for ($i = 0; $i < self::get_extended_timeout() * 10; $i++) {
07298309
RT
817 $pending = '';
818 try {
7bfb575f 819 $jscode = trim(preg_replace('/\s+/', ' ', '
5536bf4f 820 return (function() {
07298309
RT
821 if (typeof M === "undefined") {
822 if (document.readyState === "complete") {
823 return "";
824 } else {
825 return "incomplete";
826 }
827 } else if (' . self::PAGE_READY_JS . ') {
828 return "";
eb9ca848 829 } else if (typeof M.util !== "undefined") {
07298309 830 return M.util.pending_js.join(":");
eb9ca848
RT
831 } else {
832 return "incomplete"
07298309 833 }
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}