Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403]

   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   * Steps definitions related with permissions.
  19   *
  20   * @package   core
  21   * @category  test
  22   * @copyright 2013 David MonllaĆ³
  23   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
  27  
  28  require_once (__DIR__ . '/../../behat/behat_base.php');
  29  
  30  use Behat\Mink\Exception\ExpectationException as ExpectationException,
  31      Behat\Gherkin\Node\TableNode as TableNode;
  32  
  33  /**
  34   * Steps definitions to set up permissions to capabilities.
  35   *
  36   * @package   core
  37   * @category  test
  38   * @copyright 2013 David MonllaĆ³
  39   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40   */
  41  class behat_permissions extends behat_base {
  42  
  43      /**
  44       * Set system level permissions to the specified role. Expects a table with capability name and permission (Inherit/Allow/Prevent/Prohibit) columns.
  45       * @Given /^I set the following system permissions of "(?P<rolefullname_string>(?:[^"]|\\")*)" role:$/
  46       * @param string $rolename
  47       * @param TableNode $table
  48       */
  49      public function i_set_the_following_system_permissions_of_role($rolename, $table) {
  50          // Applied in the System context.
  51          $context = \context_system::instance();
  52  
  53          // Translate the specified rolename into a role.
  54          $rolenames = role_get_names($context);
  55          $matched = array_filter($rolenames, function($role) use ($rolename) {
  56              return ($role->localname === $rolename) || ($role->shortname === $rolename) || ($role->description === $rolename);
  57          });
  58  
  59          if (count($matched) === 0) {
  60              throw new ExpectationException("Unable to find a role with name '{$rolename}'", $this->getSession());
  61          } else if (count($matched) > 1) {
  62              throw new ExpectationException("Multiple roles matched '{$rolename}'", $this->getSession());
  63          }
  64  
  65          $role = reset($matched);
  66  
  67          $permissionmap = [
  68              get_string('inherit', 'role') => 'inherit',
  69              get_string('allow', 'role') => 'allow',
  70              get_string('prevent', 'role') => 'prevent',
  71              get_string('prohibit', 'role') => 'prohibit',
  72          ];
  73  
  74          $columns = ['role'];
  75          $newtabledata = [$role->shortname];
  76          foreach ($table as $data) {
  77              $columns[] = $data['capability'];
  78              $newtabledata[] = $permissionmap[$data['permission']];
  79          }
  80  
  81          $this->execute(
  82              'behat_data_generators::the_following_entities_exist',
  83              [
  84                  'role capabilities',
  85                  new TableNode([
  86                      0 => $columns,
  87                      1 => $newtabledata,
  88                  ])
  89              ]
  90          );
  91      }
  92  
  93      /**
  94       * Overrides system capabilities at category, course and module levels. This step begins after clicking 'Permissions' link. Expects a table with capability name and permission (Inherit/Allow/Prevent/Prohibit) columns.
  95       * @Given /^I override the system permissions of "(?P<rolefullname_string>(?:[^"]|\\")*)" role with:$/
  96       * @param string $rolename
  97       * @param TableNode $table
  98       */
  99      public function i_override_the_system_permissions_of_role_with($rolename, $table) {
 100  
 101          // We don't know the number of overrides so we have to get it to match the option contents.
 102          $roleoption = $this->find('xpath', '//select[@name="roleid"]/option[contains(.,"' . $this->escape($rolename) . '")]');
 103  
 104          $this->execute('behat_forms::i_set_the_field_to',
 105              array(get_string('advancedoverride', 'role'), $this->escape($roleoption->getText()))
 106          );
 107  
 108          if (!$this->running_javascript()) {
 109              $this->execute("behat_general::i_click_on_in_the", [get_string('go'), 'button', 'region-main', 'region']);
 110          }
 111  
 112          $this->execute("behat_permissions::i_fill_the_capabilities_form_with_the_following_permissions", $table);
 113  
 114          $this->execute('behat_forms::press_button', get_string('savechanges'));
 115      }
 116  
 117      /**
 118       * Fills the advanced permissions form with the provided data. Expects a table with capability name and permission (Inherit/Allow/Prevent/Prohibit) columns.
 119       * @Given /^I fill the capabilities form with the following permissions:$/
 120       * @param TableNode $table
 121       * @return void
 122       */
 123      public function i_fill_the_capabilities_form_with_the_following_permissions($table) {
 124  
 125          // Ensure we are using the advanced view.
 126          // Wrapped in a try/catch to capture the exception and continue execution, we don't know if advanced mode was already enabled.
 127          try {
 128              $advancedtoggle = $this->find_button(get_string('showadvanced', 'form'));
 129              if ($advancedtoggle) {
 130                  $advancedtoggle->click();
 131  
 132                  // Wait for the page to load.
 133                  $this->getSession()->wait(self::get_timeout() * 1000, self::PAGE_READY_JS);
 134              }
 135          } catch (Exception $e) {
 136              // We already are in advanced mode.
 137          }
 138  
 139          // Using getRows() as we are not sure if tests writers will add the header.
 140          foreach ($table->getRows() as $key => $row) {
 141  
 142              if (count($row) !== 2) {
 143                  throw new ExpectationException('You should specify a table with capability/permission columns', $this->getSession());
 144              }
 145  
 146              list($capability, $permission) = $row;
 147  
 148              // Skip the headers row if it was provided
 149              if (strtolower($capability) == 'capability' || strtolower($capability) == 'capabilities') {
 150                  continue;
 151              }
 152  
 153              // Checking the permission value.
 154              $permissionconstant = 'CAP_'. strtoupper($permission);
 155              if (!defined($permissionconstant)) {
 156                  throw new ExpectationException(
 157                      'The provided permission value "' . $permission . '" is not valid. Use Inherit, Allow, Prevent or Prohibited',
 158                      $this->getSession()
 159                  );
 160              }
 161  
 162              // Converting from permission to constant value.
 163              $permissionvalue = constant($permissionconstant);
 164  
 165              // Here we wait for the element to appear and exception if it does not exist.
 166              $radio = $this->find('xpath', '//input[@name="' . $capability . '" and @value="' . $permissionvalue . '"]');
 167              $field = behat_field_manager::get_field_instance('radio', $radio, $this->getSession());
 168              $field->set_value(1);
 169          }
 170      }
 171  
 172      /**
 173       * Checks if the capability has the specified permission. Works in the role definition advanced page.
 174       *
 175       * @Then /^"(?P<capability_string>(?:[^"]|\\")*)" capability has "(?P<permission_string>Not set|Allow|Prevent|Prohibit)" permission$/
 176       * @throws ExpectationException
 177       * @param string $capabilityname
 178       * @param string $permission
 179       * @return void
 180       */
 181      public function capability_has_permission($capabilityname, $permission) {
 182  
 183          // We already know the name, so we just need the value.
 184          $radioxpath = "//table[contains(concat(' ',
 185   normalize-space(@class), ' '), ' rolecap ')]/descendant::input[@type='radio']" .
 186              "[@name='" . $capabilityname . "'][@checked]";
 187  
 188          $checkedradio = $this->find('xpath', $radioxpath);
 189  
 190          switch ($permission) {
 191              case get_string('notset', 'role'):
 192                  $perm = CAP_INHERIT;
 193                  break;
 194              case get_string('allow', 'role'):
 195                  $perm = CAP_ALLOW;
 196                  break;
 197              case get_string('prevent', 'role'):
 198                  $perm = CAP_PREVENT;
 199                  break;
 200              case get_string('prohibit', 'role'):
 201                  $perm = CAP_PROHIBIT;
 202                  break;
 203              default:
 204                  throw new ExpectationException('"' . $permission . '" permission does not exist', $this->getSession());
 205                  break;
 206          }
 207  
 208          if ($checkedradio->getAttribute('value') != $perm) {
 209              throw new ExpectationException('"' . $capabilityname . '" permission is not "' . $permission . '"', $this->getSession());
 210          }
 211      }
 212  
 213      /**
 214       * Set the allowed role assignments for the specified role.
 215       *
 216       * @Given /^I define the allowed role assignments for the "(?P<rolefullname_string>(?:[^"]|\\")*)" role as:$/
 217       * @param string $rolename
 218       * @param TableNode $table
 219       * @return void Executes other steps
 220       */
 221      public function i_define_the_allowed_role_assignments_for_a_role_as($rolename, $table) {
 222          $parentnodes = get_string('users', 'admin') . ' > ' .
 223              get_string('permissions', 'role');
 224  
 225          // Go to home page.
 226          $this->execute("behat_general::i_am_on_homepage");
 227  
 228          // Navigate to Define roles page via site administration menu.
 229          $this->execute("behat_navigation::i_navigate_to_in_site_administration",
 230                  $parentnodes .' > '. get_string('defineroles', 'role')
 231          );
 232  
 233          $this->execute("behat_general::click_link", "Allow role assignments");
 234          $this->execute("behat_permissions::i_fill_in_the_allowed_role_assignments_form_for_a_role_with",
 235              array($rolename, $table)
 236          );
 237  
 238          $this->execute('behat_forms::press_button', get_string('savechanges'));
 239      }
 240  
 241      /**
 242       * Fill in the allowed role assignments form for the specied role.
 243       *
 244       * Takes a table with two columns. Each row should contain the target
 245       * role, and either "Assignable" or "Not assignable".
 246       *
 247       * @Given /^I fill in the allowed role assignments form for the "(?P<rolefullname_string>(?:[^"]|\\")*)" role with:$/
 248       * @param String $sourcerole
 249       * @param TableNode $table
 250       * @return void
 251       */
 252      public function i_fill_in_the_allowed_role_assignments_form_for_a_role_with($sourcerole, $table) {
 253          foreach ($table->getRows() as $key => $row) {
 254              list($targetrole, $allowed) = $row;
 255  
 256              $node = $this->find('xpath', '//input[@title="Allow users with role ' .
 257                  $sourcerole .
 258                  ' to assign the role ' .
 259                  $targetrole . '"]');
 260  
 261              if ($allowed == 'Assignable') {
 262                  if (!$node->isChecked()) {
 263                      $node->check();
 264                  }
 265              } else if ($allowed == 'Not assignable') {
 266                  if ($node->isChecked()) {
 267                      $node->uncheck();
 268                  }
 269              } else {
 270                  throw new ExpectationException(
 271                      'The provided permission value "' . $allowed . '" is not valid. Use Assignable, or Not assignable',
 272                      $this->getSession()
 273                  );
 274              }
 275          }
 276      }
 277  
 278      /**
 279       * Mark context as frozen.
 280       *
 281       * @Then /^the "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" is context frozen$/
 282       * @throws ExpectationException if the context cannot be frozen or found
 283       * @param string $element Element we look on
 284       * @param string $selector The type of where we look (activity, course)
 285       */
 286      public function the_context_is_context_frozen(string $element, string $selector) {
 287  
 288          // Enable context freeze if it is not done yet.
 289          set_config('contextlocking', 1);
 290  
 291          // Find context.
 292          $context = self::get_context($selector, $element);
 293  
 294          // Freeze context.
 295          $context->set_locked(true);
 296      }
 297  
 298      /**
 299       * Unmark context as frozen.
 300       *
 301       * @Then /^the "(?P<element_string>(?:[^"]|\\")*)" "(?P<selector_string>[^"]*)" is not context frozen$/
 302       * @throws ExpectationException if the context cannot be frozen or found
 303       * @param string $element Element we look on
 304       * @param string $selector The type of where we look (activity, course)
 305       */
 306      public function the_context_is_not_context_frozen(string $element, string $selector) {
 307  
 308          // Enable context freeze if it is not done yet.
 309          set_config('contextlocking', 1);
 310  
 311          // Find context.
 312          $context = self::get_context($selector, $element);
 313  
 314          // Freeze context.
 315          $context->set_locked(false);
 316      }
 317  }