Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 402] [Versions 39 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   * Defines the base class form used by blocks/edit.php to edit block instance configuration.
  19   *
  20   * It works with the {@link 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  if (!defined('MOODLE_INTERNAL')) {
  29      die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
  30  }
  31  
  32  require_once($CFG->libdir . '/formslib.php');
  33  require_once($CFG->libdir . '/blocklib.php');
  34  
  35  /**
  36   * The base class form used by blocks/edit.php to edit block instance configuration.
  37   *
  38   * @copyright 2009 Tim Hunt
  39   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40   */
  41  class block_edit_form extends moodleform {
  42      /**
  43       * The block instance we are editing.
  44       * @var block_base
  45       */
  46      public $block;
  47      /**
  48       * The page we are editing this block in association with.
  49       * @var moodle_page
  50       */
  51      public $page;
  52  
  53      /**
  54       * Defaults set in set_data() that need to be returned in get_data() if form elements were not created
  55       * @var array
  56       */
  57      protected $defaults = [];
  58  
  59      function __construct($actionurl, $block, $page) {
  60          global $CFG;
  61          $this->block = $block;
  62          $this->page = $page;
  63          parent::__construct($actionurl);
  64      }
  65  
  66      function definition() {
  67          $mform =& $this->_form;
  68  
  69          // First show fields specific to this type of block.
  70          $this->specific_definition($mform);
  71  
  72          // Then show the fields about where this block appears.
  73          $mform->addElement('header', 'whereheader', get_string('wherethisblockappears', 'block'));
  74  
  75          // If the current weight of the block is out-of-range, add that option in.
  76          $blockweight = $this->block->instance->weight;
  77          $weightoptions = array();
  78          if ($blockweight < -block_manager::MAX_WEIGHT) {
  79              $weightoptions[$blockweight] = $blockweight;
  80          }
  81          for ($i = -block_manager::MAX_WEIGHT; $i <= block_manager::MAX_WEIGHT; $i++) {
  82              $weightoptions[$i] = $i;
  83          }
  84          if ($blockweight > block_manager::MAX_WEIGHT) {
  85              $weightoptions[$blockweight] = $blockweight;
  86          }
  87          $first = reset($weightoptions);
  88          $weightoptions[$first] = get_string('bracketfirst', 'block', $first);
  89          $last = end($weightoptions);
  90          $weightoptions[$last] = get_string('bracketlast', 'block', $last);
  91  
  92          $regionoptions = $this->page->theme->get_all_block_regions();
  93          foreach ($this->page->blocks->get_regions() as $region) {
  94              // Make sure to add all custom regions of this particular page too.
  95              if (!isset($regionoptions[$region])) {
  96                  $regionoptions[$region] = $region;
  97              }
  98          }
  99  
 100          $parentcontext = context::instance_by_id($this->block->instance->parentcontextid);
 101          $mform->addElement('static', 'bui_homecontext', get_string('createdat', 'block'), $parentcontext->get_context_name());
 102          $mform->addHelpButton('bui_homecontext', 'createdat', 'block');
 103  
 104          // For pre-calculated (fixed) pagetype lists
 105          $pagetypelist = array();
 106  
 107          // parse pagetype patterns
 108          $bits = explode('-', $this->page->pagetype);
 109  
 110          // First of all, check if we are editing blocks @ front-page or no and
 111          // make some dark magic if so (MDL-30340) because each page context
 112          // implies one (and only one) harcoded page-type that will be set later
 113          // when processing the form data at {@link block_manager::process_url_edit()}
 114  
 115          // Front page, show the page-contexts element and set $pagetypelist to 'any page' (*)
 116          // as unique option. Processign the form will do any change if needed
 117          if ($this->is_editing_the_frontpage()) {
 118              $contextoptions = array();
 119              $contextoptions[BUI_CONTEXTS_FRONTPAGE_ONLY] = get_string('showonfrontpageonly', 'block');
 120              $contextoptions[BUI_CONTEXTS_FRONTPAGE_SUBS] = get_string('showonfrontpageandsubs', 'block');
 121              $contextoptions[BUI_CONTEXTS_ENTIRE_SITE]    = get_string('showonentiresite', 'block');
 122              $mform->addElement('select', 'bui_contexts', get_string('contexts', 'block'), $contextoptions);
 123              $mform->addHelpButton('bui_contexts', 'contexts', 'block');
 124              $pagetypelist['*'] = '*'; // This is not going to be shown ever, it's an unique option
 125  
 126          // Any other system context block, hide the page-contexts element,
 127          // it's always system-wide BUI_CONTEXTS_ENTIRE_SITE
 128          } else if ($parentcontext->contextlevel == CONTEXT_SYSTEM) {
 129  
 130          } else if ($parentcontext->contextlevel == CONTEXT_COURSE) {
 131              // 0 means display on current context only, not child contexts
 132              // but if course managers select mod-* as pagetype patterns, block system will overwrite this option
 133              // to 1 (display on current context and child contexts)
 134          } else if ($parentcontext->contextlevel == CONTEXT_MODULE or $parentcontext->contextlevel == CONTEXT_USER) {
 135              // module context doesn't have child contexts, so display in current context only
 136          } else {
 137              $parentcontextname = $parentcontext->get_context_name();
 138              $contextoptions[BUI_CONTEXTS_CURRENT]      = get_string('showoncontextonly', 'block', $parentcontextname);
 139              $contextoptions[BUI_CONTEXTS_CURRENT_SUBS] = get_string('showoncontextandsubs', 'block', $parentcontextname);
 140              $mform->addElement('select', 'bui_contexts', get_string('contexts', 'block'), $contextoptions);
 141          }
 142          $mform->setType('bui_contexts', PARAM_INT);
 143  
 144          // Generate pagetype patterns by callbacks if necessary (has not been set specifically)
 145          if (empty($pagetypelist)) {
 146              $pagetypelist = generate_page_type_patterns($this->page->pagetype, $parentcontext, $this->page->context);
 147              $displaypagetypewarning = false;
 148              if (!array_key_exists($this->block->instance->pagetypepattern, $pagetypelist)) {
 149                  // Pushing block's existing page type pattern
 150                  $pagetypestringname = 'page-'.str_replace('*', 'x', $this->block->instance->pagetypepattern);
 151                  if (get_string_manager()->string_exists($pagetypestringname, 'pagetype')) {
 152                      $pagetypelist[$this->block->instance->pagetypepattern] = get_string($pagetypestringname, 'pagetype');
 153                  } else {
 154                      //as a last resort we could put the page type pattern in the select box
 155                      //however this causes mod-data-view to be added if the only option available is mod-data-*
 156                      // so we are just showing a warning to users about their prev setting being reset
 157                      $displaypagetypewarning = true;
 158                  }
 159              }
 160          }
 161  
 162          // hide page type pattern select box if there is only one choice
 163          if (count($pagetypelist) > 1) {
 164              if ($displaypagetypewarning) {
 165                  $mform->addElement('static', 'pagetypewarning', '', get_string('pagetypewarning','block'));
 166              }
 167  
 168              $mform->addElement('select', 'bui_pagetypepattern', get_string('restrictpagetypes', 'block'), $pagetypelist);
 169          } else {
 170              $values = array_keys($pagetypelist);
 171              $value = array_pop($values);
 172              // Now we are really hiding a lot (both page-contexts and page-type-patterns),
 173              // specially in some systemcontext pages having only one option (my/user...)
 174              // so, until it's decided if we are going to add the 'bring-back' pattern to
 175              // all those pages or no (see MDL-30574), we are going to show the unique
 176              // element statically
 177              // TODO: Revisit this once MDL-30574 has been decided and implemented, although
 178              // perhaps it's not bad to always show this statically when only one pattern is
 179              // available.
 180              if (!$this->is_editing_the_frontpage()) {
 181                  // Try to beautify it
 182                  $strvalue = $value;
 183                  $strkey = 'page-'.str_replace('*', 'x', $strvalue);
 184                  if (get_string_manager()->string_exists($strkey, 'pagetype')) {
 185                      $strvalue = get_string($strkey, 'pagetype');
 186                  }
 187                  // Show as static (hidden has been set already)
 188                  $mform->addElement('static', 'bui_staticpagetypepattern',
 189                      get_string('restrictpagetypes','block'), $strvalue);
 190              }
 191          }
 192  
 193          if ($this->page->subpage) {
 194              if ($parentcontext->contextlevel != CONTEXT_USER) {
 195                  $subpageoptions = array(
 196                      '%@NULL@%' => get_string('anypagematchingtheabove', 'block'),
 197                      $this->page->subpage => get_string('thisspecificpage', 'block', $this->page->subpage),
 198                  );
 199                  $mform->addElement('select', 'bui_subpagepattern', get_string('subpages', 'block'), $subpageoptions);
 200              }
 201          }
 202  
 203          $defaultregionoptions = $regionoptions;
 204          $defaultregion = $this->block->instance->defaultregion;
 205          if (!array_key_exists($defaultregion, $defaultregionoptions)) {
 206              $defaultregionoptions[$defaultregion] = $defaultregion;
 207          }
 208          $mform->addElement('select', 'bui_defaultregion', get_string('defaultregion', 'block'), $defaultregionoptions);
 209          $mform->addHelpButton('bui_defaultregion', 'defaultregion', 'block');
 210  
 211          $mform->addElement('select', 'bui_defaultweight', get_string('defaultweight', 'block'), $weightoptions);
 212          $mform->addHelpButton('bui_defaultweight', 'defaultweight', 'block');
 213  
 214          // Where this block is positioned on this page.
 215          $mform->addElement('header', 'onthispage', get_string('onthispage', 'block'));
 216  
 217          $mform->addElement('selectyesno', 'bui_visible', get_string('visible', 'block'));
 218  
 219          $blockregion = $this->block->instance->region;
 220          if (!array_key_exists($blockregion, $regionoptions)) {
 221              $regionoptions[$blockregion] = $blockregion;
 222          }
 223          $mform->addElement('select', 'bui_region', get_string('region', 'block'), $regionoptions);
 224  
 225          $mform->addElement('select', 'bui_weight', get_string('weight', 'block'), $weightoptions);
 226  
 227          $pagefields = array('bui_visible', 'bui_region', 'bui_weight');
 228          if (!$this->block->user_can_edit()) {
 229              $mform->hardFreezeAllVisibleExcept($pagefields);
 230          }
 231          if (!$this->page->user_can_edit_blocks()) {
 232              $mform->hardFreeze($pagefields);
 233          }
 234  
 235          $this->add_action_buttons();
 236      }
 237  
 238      /**
 239       * Returns true if the user is editing a frontpage.
 240       * @return bool
 241       */
 242      public function is_editing_the_frontpage() {
 243          // There are some conditions to check related to contexts.
 244          $ctxconditions = $this->page->context->contextlevel == CONTEXT_COURSE &&
 245              $this->page->context->instanceid == get_site()->id;
 246          $issiteindex = (strpos($this->page->pagetype, 'site-index') === 0);
 247          // So now we can be 100% sure if edition is happening at frontpage.
 248          return ($ctxconditions && $issiteindex);
 249      }
 250  
 251      function set_data($defaults) {
 252          // Prefix bui_ on all the core field names.
 253          $blockfields = array('showinsubcontexts', 'pagetypepattern', 'subpagepattern', 'parentcontextid',
 254                  'defaultregion', 'defaultweight', 'visible', 'region', 'weight');
 255          foreach ($blockfields as $field) {
 256              $newname = 'bui_' . $field;
 257              $defaults->$newname = $defaults->$field;
 258          }
 259  
 260          // Copy block config into config_ fields.
 261          if (!empty($this->block->config)) {
 262              foreach ($this->block->config as $field => $value) {
 263                  $configfield = 'config_' . $field;
 264                  $defaults->$configfield = $value;
 265              }
 266          }
 267  
 268          // Munge ->subpagepattern becuase HTML selects don't play nicely with NULLs.
 269          if (empty($defaults->bui_subpagepattern)) {
 270              $defaults->bui_subpagepattern = '%@NULL@%';
 271          }
 272  
 273          $systemcontext = context_system::instance();
 274          if ($defaults->parentcontextid == $systemcontext->id) {
 275              $defaults->bui_contexts = BUI_CONTEXTS_ENTIRE_SITE; // System-wide and sticky
 276          } else {
 277              $defaults->bui_contexts = $defaults->bui_showinsubcontexts;
 278          }
 279  
 280          // Some fields may not be editable, remember the values here so we can return them in get_data().
 281          $this->defaults = [
 282              'bui_parentcontextid' => $defaults->bui_parentcontextid,
 283              'bui_contexts' => $defaults->bui_contexts,
 284              'bui_pagetypepattern' => $defaults->bui_pagetypepattern,
 285              'bui_subpagepattern' => $defaults->bui_subpagepattern,
 286          ];
 287          parent::set_data($defaults);
 288      }
 289  
 290      /**
 291       * Override this to create any form fields specific to this type of block.
 292       * @param object $mform the form being built.
 293       */
 294      protected function specific_definition($mform) {
 295          // By default, do nothing.
 296      }
 297  
 298      /**
 299       * Return submitted data if properly submitted or returns NULL if validation fails or
 300       * if there is no submitted data.
 301       *
 302       * @return object submitted data; NULL if not valid or not submitted or cancelled
 303       */
 304      public function get_data() {
 305          if ($data = parent::get_data()) {
 306              // Blocklib expects 'bui_editingatfrontpage' property to be returned from this form.
 307              $data->bui_editingatfrontpage = $this->is_editing_the_frontpage();
 308              // Some fields are non-editable and we need to populate them with the values from set_data().
 309              return (object)((array)$data + $this->defaults);
 310          }
 311          return $data;
 312      }
 313  }