Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

   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   * Defines the base class form used by blocks/edit.php to edit block instance configuration.
  19   *
  20   * It works with the {@see block_edit_form} class, or rather the particular
  21   * subclass defined by this block, to do the editing.
  22   *
  23   * @package    core_block
  24   * @copyright  2009 Tim Hunt
  25   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  require_once($CFG->libdir . '/blocklib.php');
  29  
  30  /**
  31   * The base class form used by blocks/edit.php to edit block instance configuration.
  32   *
  33   * @property-read block_base $block
  34   * @property-read moodle_page $page
  35   * @copyright 2009 Tim Hunt
  36   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class block_edit_form extends \core_form\dynamic_form {
  39      /**
  40       * The block instance we are editing.
  41       * @var block_base
  42       */
  43      private $_block;
  44      /**
  45       * The page we are editing this block in association with.
  46       * @var moodle_page
  47       */
  48      private $_page;
  49  
  50      /**
  51       * Defaults set in set_data() that need to be returned in get_data() if form elements were not created
  52       * @var array
  53       */
  54      protected $defaults = [];
  55  
  56      /**
  57       * Magic getter for backward compatibility
  58       *
  59       * @param string $name
  60       * @return block_base|moodle_page
  61       */
  62      public function __get(string $name) {
  63          if ($name === 'page') {
  64              return $this->get_page();
  65          } else if ($name === 'block') {
  66              return $this->get_block();
  67          } else {
  68              throw new coding_exception('Property '.$name.' does not exist');
  69          }
  70      }
  71  
  72      /**
  73       * Page where we are adding or editing the block
  74       *
  75       * To access you can also use magic property $this->page
  76       *
  77       * @return moodle_page
  78       * @throws moodle_exception
  79       */
  80      protected function get_page(): moodle_page {
  81          if (!$this->_page && !empty($this->_customdata['page'])) {
  82              $this->_page = $this->_customdata['page'];
  83          } else if (!$this->_page) {
  84              if (!$pagehash = $this->optional_param('pagehash', '', PARAM_ALPHANUMEXT)) {
  85                  throw new \moodle_exception('missingparam', '', '', 'pagehash');
  86              }
  87              $this->_page = moodle_page::retrieve_edited_page($pagehash, MUST_EXIST);
  88              $this->_page->blocks->load_blocks();
  89          }
  90          return $this->_page;
  91      }
  92  
  93      /**
  94       * Instance of the block that is being added or edited
  95       *
  96       * To access you can also use magic property $this->block
  97       *
  98       * If {{@see self::display_form_when_adding()}} returns true and the configuration
  99       * form is displayed when adding block, the $this->block->id will be null.
 100       *
 101       * @return block_base
 102       * @throws block_not_on_page_exception
 103       * @throws moodle_exception
 104       */
 105      protected function get_block(): block_base {
 106          if (!$this->_block && !empty($this->_customdata['block'])) {
 107              $this->_block = $this->_customdata['block'];
 108          } else if (!$this->_block) {
 109              $blockid = $this->optional_param('blockid', null, PARAM_INT);
 110              $blockname = $this->optional_param('blockname', null, PARAM_PLUGIN);
 111              if ($blockname && !$blockid) {
 112                  $this->_block = block_instance($blockname);
 113                  $this->_block->page = $this->page;
 114                  $this->_block->context = $this->page->context;
 115                  $this->_block->instance = (object)['parentcontextid' => $this->page->context->id, 'id' => null];
 116              } else {
 117                  $this->_block = $this->page->blocks->find_instance($blockid);
 118              }
 119          }
 120          return $this->_block;
 121      }
 122  
 123      /**
 124       * Form definition
 125       */
 126      function definition() {
 127          $mform =& $this->_form;
 128  
 129          $mform->addElement('hidden', 'blockid', $this->block->instance->id);
 130          $mform->setType('blockid', PARAM_INT);
 131          $mform->addElement('hidden', 'blockname', $this->optional_param('blockname', null, PARAM_PLUGIN));
 132          $mform->setType('blockname', PARAM_PLUGIN);
 133          $mform->addElement('hidden', 'blockregion', $this->optional_param('blockregion', null, PARAM_TEXT));
 134          $mform->setType('blockregion', PARAM_TEXT);
 135          $mform->addElement('hidden', 'pagehash', $this->optional_param('pagehash', null, PARAM_ALPHANUMEXT));
 136          $mform->setType('pagehash', PARAM_ALPHANUMEXT);
 137  
 138          // First show fields specific to this type of block.
 139          $this->specific_definition($mform);
 140  
 141          if (!$this->block->instance->id) {
 142              return;
 143          }
 144  
 145          // Then show the fields about where this block appears.
 146          $mform->addElement('header', 'whereheader', get_string('wherethisblockappears', 'block'));
 147  
 148          // If the current weight of the block is out-of-range, add that option in.
 149          $blockweight = $this->block->instance->weight;
 150          $weightoptions = array();
 151          if ($blockweight < -block_manager::MAX_WEIGHT) {
 152              $weightoptions[$blockweight] = $blockweight;
 153          }
 154          for ($i = -block_manager::MAX_WEIGHT; $i <= block_manager::MAX_WEIGHT; $i++) {
 155              $weightoptions[$i] = $i;
 156          }
 157          if ($blockweight > block_manager::MAX_WEIGHT) {
 158              $weightoptions[$blockweight] = $blockweight;
 159          }
 160          $first = reset($weightoptions);
 161          $weightoptions[$first] = get_string('bracketfirst', 'block', $first);
 162          $last = end($weightoptions);
 163          $weightoptions[$last] = get_string('bracketlast', 'block', $last);
 164  
 165          $regionoptions = $this->page->theme->get_all_block_regions();
 166          foreach ($this->page->blocks->get_regions() as $region) {
 167              // Make sure to add all custom regions of this particular page too.
 168              if (!isset($regionoptions[$region])) {
 169                  $regionoptions[$region] = $region;
 170              }
 171          }
 172  
 173          $parentcontext = context::instance_by_id($this->block->instance->parentcontextid);
 174          $mform->addElement('static', 'bui_homecontext', get_string('createdat', 'block'), $parentcontext->get_context_name());
 175          $mform->addHelpButton('bui_homecontext', 'createdat', 'block');
 176  
 177          // For pre-calculated (fixed) pagetype lists
 178          $pagetypelist = array();
 179  
 180          // parse pagetype patterns
 181          $bits = explode('-', $this->page->pagetype);
 182  
 183          // First of all, check if we are editing blocks @ front-page or no and
 184          // make some dark magic if so (MDL-30340) because each page context
 185          // implies one (and only one) harcoded page-type that will be set later
 186          // when processing the form data at {@see block_manager::process_url_edit()}.
 187  
 188          // Front page, show the page-contexts element and set $pagetypelist to 'any page' (*)
 189          // as unique option. Processign the form will do any change if needed.
 190          if ($this->is_editing_the_frontpage()) {
 191              $contextoptions = array();
 192              $contextoptions[BUI_CONTEXTS_FRONTPAGE_ONLY] = get_string('showonfrontpageonly', 'block');
 193              $contextoptions[BUI_CONTEXTS_FRONTPAGE_SUBS] = get_string('showonfrontpageandsubs', 'block');
 194              $contextoptions[BUI_CONTEXTS_ENTIRE_SITE]    = get_string('showonentiresite', 'block');
 195              $mform->addElement('select', 'bui_contexts', get_string('contexts', 'block'), $contextoptions);
 196              $mform->addHelpButton('bui_contexts', 'contexts', 'block');
 197              $pagetypelist['*'] = '*'; // This is not going to be shown ever, it's an unique option
 198  
 199          // Any other system context block, hide the page-contexts element,
 200          // it's always system-wide BUI_CONTEXTS_ENTIRE_SITE
 201          } else if ($parentcontext->contextlevel == CONTEXT_SYSTEM) {
 202  
 203          } else if ($parentcontext->contextlevel == CONTEXT_COURSE) {
 204              // 0 means display on current context only, not child contexts
 205              // but if course managers select mod-* as pagetype patterns, block system will overwrite this option
 206              // to 1 (display on current context and child contexts)
 207          } else if ($parentcontext->contextlevel == CONTEXT_MODULE or $parentcontext->contextlevel == CONTEXT_USER) {
 208              // module context doesn't have child contexts, so display in current context only
 209          } else {
 210              $parentcontextname = $parentcontext->get_context_name();
 211              $contextoptions[BUI_CONTEXTS_CURRENT]      = get_string('showoncontextonly', 'block', $parentcontextname);
 212              $contextoptions[BUI_CONTEXTS_CURRENT_SUBS] = get_string('showoncontextandsubs', 'block', $parentcontextname);
 213              $mform->addElement('select', 'bui_contexts', get_string('contexts', 'block'), $contextoptions);
 214          }
 215          $mform->setType('bui_contexts', PARAM_INT);
 216  
 217          // Generate pagetype patterns by callbacks if necessary (has not been set specifically)
 218          if (empty($pagetypelist)) {
 219              $pagetypelist = generate_page_type_patterns($this->page->pagetype, $parentcontext, $this->page->context);
 220              $displaypagetypewarning = false;
 221              if (!array_key_exists($this->block->instance->pagetypepattern, $pagetypelist)) {
 222                  // Pushing block's existing page type pattern
 223                  $pagetypestringname = 'page-'.str_replace('*', 'x', $this->block->instance->pagetypepattern);
 224                  if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
 225                      $pagetypelist[$this->block->instance->pagetypepattern] = get_string($pagetypestringname, 'pagetype');
 226                  } else {
 227                      //as a last resort we could put the page type pattern in the select box
 228                      //however this causes mod-data-view to be added if the only option available is mod-data-*
 229                      // so we are just showing a warning to users about their prev setting being reset
 230                      $displaypagetypewarning = true;
 231                  }
 232              }
 233          }
 234  
 235          // hide page type pattern select box if there is only one choice
 236          if (count($pagetypelist) > 1) {
 237              if ($displaypagetypewarning) {
 238                  $mform->addElement('static', 'pagetypewarning', '', get_string('pagetypewarning','block'));
 239              }
 240  
 241              $mform->addElement('select', 'bui_pagetypepattern', get_string('restrictpagetypes', 'block'), $pagetypelist);
 242          } else {
 243              $values = array_keys($pagetypelist);
 244              $value = array_pop($values);
 245              // Now we are really hiding a lot (both page-contexts and page-type-patterns),
 246              // specially in some systemcontext pages having only one option (my/user...)
 247              // so, until it's decided if we are going to add the 'bring-back' pattern to
 248              // all those pages or no (see MDL-30574), we are going to show the unique
 249              // element statically
 250              // TODO: Revisit this once MDL-30574 has been decided and implemented, although
 251              // perhaps it's not bad to always show this statically when only one pattern is
 252              // available.
 253              if (!$this->is_editing_the_frontpage()) {
 254                  // Try to beautify it
 255                  $strvalue = $value;
 256                  $strkey = 'page-'.str_replace('*', 'x', $strvalue);
 257                  if (get_string_manager()->string_exists($strkey, 'pagetype')) {
 258                      $strvalue = get_string($strkey, 'pagetype');
 259                  }
 260                  // Show as static (hidden has been set already)
 261                  $mform->addElement('static', 'bui_staticpagetypepattern',
 262                      get_string('restrictpagetypes','block'), $strvalue);
 263              }
 264          }
 265  
 266          if ($this->page->subpage) {
 267              if ($parentcontext->contextlevel != CONTEXT_USER) {
 268                  $subpageoptions = array(
 269                      '%@NULL@%' => get_string('anypagematchingtheabove', 'block'),
 270                      $this->page->subpage => get_string('thisspecificpage', 'block', $this->page->subpage),
 271                  );
 272                  $mform->addElement('select', 'bui_subpagepattern', get_string('subpages', 'block'), $subpageoptions);
 273              }
 274          }
 275  
 276          $defaultregionoptions = $regionoptions;
 277          $defaultregion = $this->block->instance->defaultregion;
 278          if (!array_key_exists($defaultregion, $defaultregionoptions)) {
 279              $defaultregionoptions[$defaultregion] = $defaultregion;
 280          }
 281          $mform->addElement('select', 'bui_defaultregion', get_string('defaultregion', 'block'), $defaultregionoptions);
 282          $mform->addHelpButton('bui_defaultregion', 'defaultregion', 'block');
 283  
 284          $mform->addElement('select', 'bui_defaultweight', get_string('defaultweight', 'block'), $weightoptions);
 285          $mform->addHelpButton('bui_defaultweight', 'defaultweight', 'block');
 286  
 287          // Where this block is positioned on this page.
 288          $mform->addElement('header', 'onthispage', get_string('onthispage', 'block'));
 289  
 290          $mform->addElement('selectyesno', 'bui_visible', get_string('visible', 'block'));
 291  
 292          $blockregion = $this->block->instance->region;
 293          if (!array_key_exists($blockregion, $regionoptions)) {
 294              $regionoptions[$blockregion] = $blockregion;
 295          }
 296          $mform->addElement('select', 'bui_region', get_string('region', 'block'), $regionoptions);
 297  
 298          $mform->addElement('select', 'bui_weight', get_string('weight', 'block'), $weightoptions);
 299  
 300          $pagefields = array('bui_visible', 'bui_region', 'bui_weight');
 301          if (!$this->block->user_can_edit()) {
 302              $mform->hardFreezeAllVisibleExcept($pagefields);
 303          }
 304          if (!$this->page->user_can_edit_blocks()) {
 305              $mform->hardFreeze($pagefields);
 306          }
 307  
 308          if (!empty($this->_customdata['actionbuttons'])) {
 309              $this->add_action_buttons();
 310          }
 311      }
 312  
 313      /**
 314       * Returns true if the user is editing a frontpage.
 315       * @return bool
 316       */
 317      public function is_editing_the_frontpage() {
 318          // There are some conditions to check related to contexts.
 319          $ctxconditions = $this->page->context->contextlevel == CONTEXT_COURSE &&
 320              $this->page->context->instanceid == get_site()->id;
 321          $issiteindex = (strpos($this->page->pagetype, 'site-index') === 0);
 322          // So now we can be 100% sure if edition is happening at frontpage.
 323          return ($ctxconditions && $issiteindex);
 324      }
 325  
 326      /**
 327       * Prepare block configuration data and add default values when needed
 328       *
 329       * @param stdClass $defaults
 330       * @return stdClass
 331       */
 332      protected function prepare_defaults(stdClass $defaults): stdClass {
 333          // Prefix bui_ on all the core field names.
 334          $blockfields = array('showinsubcontexts', 'pagetypepattern', 'subpagepattern', 'parentcontextid',
 335                  'defaultregion', 'defaultweight', 'visible', 'region', 'weight');
 336          foreach ($blockfields as $field) {
 337              $newname = 'bui_' . $field;
 338              $defaults->$newname = $defaults->$field ?? null;
 339          }
 340  
 341          // Copy block config into config_ fields.
 342          if (!empty($this->block->config)) {
 343              foreach ($this->block->config as $field => $value) {
 344                  $configfield = 'config_' . $field;
 345                  $defaults->$configfield = $value;
 346              }
 347          }
 348  
 349          // Munge ->subpagepattern becuase HTML selects don't play nicely with NULLs.
 350          if (empty($defaults->bui_subpagepattern)) {
 351              $defaults->bui_subpagepattern = '%@NULL@%';
 352          }
 353  
 354          $systemcontext = context_system::instance();
 355          if ($defaults->parentcontextid == $systemcontext->id) {
 356              $defaults->bui_contexts = BUI_CONTEXTS_ENTIRE_SITE; // System-wide and sticky
 357          } else {
 358              $defaults->bui_contexts = $defaults->bui_showinsubcontexts;
 359          }
 360  
 361          // Some fields may not be editable, remember the values here so we can return them in get_data().
 362          $this->defaults = [
 363              'bui_parentcontextid' => $defaults->bui_parentcontextid,
 364              'bui_contexts' => $defaults->bui_contexts,
 365              'bui_pagetypepattern' => $defaults->bui_pagetypepattern,
 366              'bui_subpagepattern' => $defaults->bui_subpagepattern,
 367          ];
 368          return $defaults;
 369      }
 370  
 371      /**
 372       * Load in existing data as form defaults
 373       *
 374       * @param stdClass $defaults
 375       * @return void
 376       */
 377      public function set_data($defaults) {
 378          parent::set_data($this->prepare_defaults($defaults));
 379      }
 380  
 381      /**
 382       * Override this to create any form fields specific to this type of block.
 383       * @param \MoodleQuickForm $mform the form being built.
 384       */
 385      protected function specific_definition($mform) {
 386          // By default, do nothing.
 387      }
 388  
 389      /**
 390       * Return submitted data if properly submitted or returns NULL if validation fails or
 391       * if there is no submitted data.
 392       *
 393       * @return stdClass submitted data; NULL if not valid or not submitted or cancelled
 394       */
 395      public function get_data() {
 396          if ($data = parent::get_data()) {
 397              // Blocklib expects 'bui_editingatfrontpage' property to be returned from this form.
 398              $data->bui_editingatfrontpage = $this->is_editing_the_frontpage();
 399              // Some fields are non-editable and we need to populate them with the values from set_data().
 400              return (object)((array)$data + $this->defaults);
 401          }
 402          return $data;
 403      }
 404  
 405      /**
 406       * Returns context where this form is used
 407       *
 408       * @return context
 409       */
 410      protected function get_context_for_dynamic_submission(): context {
 411          return $this->page->context;
 412      }
 413  
 414      /**
 415       * Checks if current user has access to this form, otherwise throws exception
 416       */
 417      protected function check_access_for_dynamic_submission(): void {
 418          if ($this->block->instance->id) {
 419              if (!$this->page->user_can_edit_blocks() && !$this->block->user_can_edit()) {
 420                  throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock'));
 421              }
 422          } else {
 423              if (!$this->page->user_can_edit_blocks()) {
 424                  throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('addblock'));
 425              }
 426              $addableblocks = $this->page->blocks->get_addable_blocks();
 427              $blocktype = $this->block->name();
 428              if (!array_key_exists($blocktype, $addableblocks)) {
 429                  throw new moodle_exception('cannotaddthisblocktype', '', $this->page->url->out(), $blocktype);
 430              }
 431          }
 432      }
 433  
 434      /**
 435       * Process the form submission, used if form was submitted via AJAX
 436       */
 437      public function process_dynamic_submission() {
 438          if ($this->block->instance->id) {
 439              $this->page->blocks->save_block_data($this->block, $this->get_data());
 440          } else {
 441              $blockregion = $this->optional_param('blockregion', null, PARAM_TEXT);
 442              $newblock = $this->page->blocks->add_block_at_end_of_default_region($this->block->name(),
 443                  empty($blockregion) ? null : $blockregion);
 444              $this->page->blocks->load_blocks();
 445              $newblock = $this->page->blocks->find_instance($newblock->instance->id);
 446              $newdata = $this->prepare_defaults($newblock->instance);
 447              foreach ($this->get_data() as $key => $value) {
 448                  $newdata->$key = $value;
 449              }
 450              $this->page->blocks->save_block_data($newblock, $newdata);
 451          }
 452      }
 453  
 454      /**
 455       * Load in existing data as form defaults
 456       */
 457      public function set_data_for_dynamic_submission(): void {
 458          $this->set_data($this->block->instance);
 459      }
 460  
 461      /**
 462       * Returns url to set in $PAGE->set_url() when form is being rendered or submitted via AJAX
 463       *
 464       * @return moodle_url
 465       */
 466      protected function get_page_url_for_dynamic_submission(): moodle_url {
 467          return $this->page->url;
 468      }
 469  
 470      /**
 471       * Display the configuration form when block is being added to the page
 472       *
 473       * By default when block is added to the page it is added with the default configuration.
 474       * Some block may require configuration, for example, "glossary random entry" block
 475       * needs a glossary to be selected, "RSS feed" block needs an RSS feed to be selected, etc.
 476       *
 477       * Such blocks can override this function and return true. These blocks must
 478       * ensure that the function specific_definition() will work if there is no current block id.
 479       *
 480       * @return bool
 481       */
 482      public static function display_form_when_adding(): bool {
 483          return false;
 484      }
 485  }