Merge branch 'MDL-66404-master' of git://github.com/cescobedo/moodle
[moodle.git] / blocks / moodleblock.class.php
blobdd45eeda343538274a9035a8fbacec54a8f37298
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.
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/>.
17 /**
18 * This file contains the parent class for moodle blocks, block_base.
20 * @package core_block
21 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
24 /// Constants
26 /**
27 * Block type of list. Contents of block should be set as an associative array in the content object as items ($this->content->items). Optionally include footer text in $this->content->footer.
29 define('BLOCK_TYPE_LIST', 1);
31 /**
32 * Block type of text. Contents of block should be set to standard html text in the content object as items ($this->content->text). Optionally include footer text in $this->content->footer.
34 define('BLOCK_TYPE_TEXT', 2);
35 /**
36 * Block type of tree. $this->content->items is a list of tree_item objects and $this->content->footer is a string.
38 define('BLOCK_TYPE_TREE', 3);
40 /**
41 * Class for describing a moodle block, all Moodle blocks derive from this class
43 * @author Jon Papaioannou
44 * @package core_block
46 class block_base {
48 /**
49 * Internal var for storing/caching translated strings
50 * @var string $str
52 var $str;
54 /**
55 * The title of the block to be displayed in the block title area.
56 * @var string $title
58 var $title = NULL;
60 /**
61 * The name of the block to be displayed in the block title area if the title is empty.
62 * @var string arialabel
64 var $arialabel = NULL;
66 /**
67 * The type of content that this block creates. Currently support options - BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT
68 * @var int $content_type
70 var $content_type = BLOCK_TYPE_TEXT;
72 /**
73 * An object to contain the information to be displayed in the block.
74 * @var stdObject $content
76 var $content = NULL;
78 /**
79 * The initialized instance of this block object.
80 * @var block $instance
82 var $instance = NULL;
84 /**
85 * The page that this block is appearing on.
86 * @var moodle_page
88 public $page = NULL;
90 /**
91 * This blocks's context.
92 * @var stdClass
94 public $context = NULL;
96 /**
97 * An object containing the instance configuration information for the current instance of this block.
98 * @var stdObject $config
100 var $config = NULL;
103 * How often the cronjob should run, 0 if not at all.
104 * @var int $cron
107 var $cron = NULL;
109 /// Class Functions
112 * Fake constructor to keep PHP5 happy
115 function __construct() {
116 $this->init();
120 * Function that can be overridden to do extra cleanup before
121 * the database tables are deleted. (Called once per block, not per instance!)
123 function before_delete() {
127 * Returns the block name, as present in the class name,
128 * the database, the block directory, etc etc.
130 * @return string
132 function name() {
133 // Returns the block name, as present in the class name,
134 // the database, the block directory, etc etc.
135 static $myname;
136 if ($myname === NULL) {
137 $myname = strtolower(get_class($this));
138 $myname = substr($myname, strpos($myname, '_') + 1);
140 return $myname;
144 * Parent class version of this function simply returns NULL
145 * This should be implemented by the derived class to return
146 * the content object.
148 * @return stdObject
150 function get_content() {
151 // This should be implemented by the derived class.
152 return NULL;
156 * Returns the class $title var value.
158 * Intentionally doesn't check if a title is set.
159 * This is already done in {@link _self_test()}
161 * @return string $this->title
163 function get_title() {
164 // Intentionally doesn't check if a title is set. This is already done in _self_test()
165 return $this->title;
169 * Returns the class $content_type var value.
171 * Intentionally doesn't check if content_type is set.
172 * This is already done in {@link _self_test()}
174 * @return string $this->content_type
176 function get_content_type() {
177 // Intentionally doesn't check if a content_type is set. This is already done in _self_test()
178 return $this->content_type;
182 * Returns true or false, depending on whether this block has any content to display
183 * and whether the user has permission to view the block
185 * @return boolean
187 function is_empty() {
188 if ( !has_capability('moodle/block:view', $this->context) ) {
189 return true;
192 $this->get_content();
193 return(empty($this->content->text) && empty($this->content->footer));
197 * First sets the current value of $this->content to NULL
198 * then calls the block's {@link get_content()} function
199 * to set its value back.
201 * @return stdObject
203 function refresh_content() {
204 // Nothing special here, depends on content()
205 $this->content = NULL;
206 return $this->get_content();
210 * Return a block_contents object representing the full contents of this block.
212 * This internally calls ->get_content(), and then adds the editing controls etc.
214 * You probably should not override this method, but instead override
215 * {@link html_attributes()}, {@link formatted_contents()} or {@link get_content()},
216 * {@link hide_header()}, {@link (get_edit_controls)}, etc.
218 * @return block_contents a representation of the block, for rendering.
219 * @since Moodle 2.0.
221 public function get_content_for_output($output) {
222 global $CFG;
224 $bc = new block_contents($this->html_attributes());
225 $bc->attributes['data-block'] = $this->name();
226 $bc->blockinstanceid = $this->instance->id;
227 $bc->blockpositionid = $this->instance->blockpositionid;
229 if ($this->instance->visible) {
230 $bc->content = $this->formatted_contents($output);
231 if (!empty($this->content->footer)) {
232 $bc->footer = $this->content->footer;
234 } else {
235 $bc->add_class('invisibleblock');
238 if (!$this->hide_header()) {
239 $bc->title = $this->title;
242 if (empty($bc->title)) {
243 $bc->arialabel = new lang_string('pluginname', get_class($this));
244 $this->arialabel = $bc->arialabel;
247 if ($this->page->user_is_editing()) {
248 $bc->controls = $this->page->blocks->edit_controls($this);
249 } else {
250 // we must not use is_empty on hidden blocks
251 if ($this->is_empty() && !$bc->controls) {
252 return null;
256 if (empty($CFG->allowuserblockhiding)
257 || (empty($bc->content) && empty($bc->footer))
258 || !$this->instance_can_be_collapsed()) {
259 $bc->collapsible = block_contents::NOT_HIDEABLE;
260 } else if (get_user_preferences('block' . $bc->blockinstanceid . 'hidden', false)) {
261 $bc->collapsible = block_contents::HIDDEN;
262 } else {
263 $bc->collapsible = block_contents::VISIBLE;
266 if ($this->instance_can_be_docked() && !$this->hide_header()) {
267 $bc->dockable = true;
270 $bc->annotation = ''; // TODO MDL-19398 need to work out what to say here.
272 return $bc;
277 * Return an object containing all the block content to be returned by external functions.
279 * If your block is returning formatted content or provide files for download, you should override this method to use the
280 * external_format_text, external_format_string functions for formatting or external_util::get_area_files for files.
282 * @param core_renderer $output the rendered used for output
283 * @return stdClass object containing the block title, central content, footer and linked files (if any).
284 * @since Moodle 3.6
286 public function get_content_for_external($output) {
287 $bc = new stdClass;
288 $bc->title = null;
289 $bc->content = null;
290 $bc->contentformat = FORMAT_HTML;
291 $bc->footer = null;
292 $bc->files = [];
294 if ($this->instance->visible) {
295 $bc->content = $this->formatted_contents($output);
296 if (!empty($this->content->footer)) {
297 $bc->footer = $this->content->footer;
301 if (!$this->hide_header()) {
302 $bc->title = $this->title;
305 return $bc;
309 * Return the plugin config settings for external functions.
311 * In some cases the configs will need formatting or be returned only if the current user has some capabilities enabled.
313 * @return stdClass the configs for both the block instance and plugin (as object with name -> value)
314 * @since Moodle 3.8
316 public function get_config_for_external() {
317 return (object) [
318 'instance' => new stdClass(),
319 'plugin' => new stdClass(),
324 * Convert the contents of the block to HTML.
326 * This is used by block base classes like block_list to convert the structured
327 * $this->content->list and $this->content->icons arrays to HTML. So, in most
328 * blocks, you probaby want to override the {@link get_contents()} method,
329 * which generates that structured representation of the contents.
331 * @param $output The core_renderer to use when generating the output.
332 * @return string the HTML that should appearn in the body of the block.
333 * @since Moodle 2.0.
335 protected function formatted_contents($output) {
336 $this->get_content();
337 $this->get_required_javascript();
338 if (!empty($this->content->text)) {
339 return $this->content->text;
340 } else {
341 return '';
346 * Tests if this block has been implemented correctly.
347 * Also, $errors isn't used right now
349 * @return boolean
352 function _self_test() {
353 // Tests if this block has been implemented correctly.
354 // Also, $errors isn't used right now
355 $errors = array();
357 $correct = true;
358 if ($this->get_title() === NULL) {
359 $errors[] = 'title_not_set';
360 $correct = false;
362 if (!in_array($this->get_content_type(), array(BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT, BLOCK_TYPE_TREE))) {
363 $errors[] = 'invalid_content_type';
364 $correct = false;
366 //following selftest was not working when roles&capabilities were used from block
367 /* if ($this->get_content() === NULL) {
368 $errors[] = 'content_not_set';
369 $correct = false;
371 $formats = $this->applicable_formats();
372 if (empty($formats) || array_sum($formats) === 0) {
373 $errors[] = 'no_formats';
374 $correct = false;
377 return $correct;
381 * Subclasses should override this and return true if the
382 * subclass block has a settings.php file.
384 * @return boolean
386 function has_config() {
387 return false;
391 * Default behavior: save all variables as $CFG properties
392 * You don't need to override this if you 're satisfied with the above
394 * @deprecated since Moodle 2.9 MDL-49385 - Please use Admin Settings functionality to save block configuration.
396 function config_save($data) {
397 throw new coding_exception('config_save() can not be used any more, use Admin Settings functionality to save block configuration.');
401 * Which page types this block may appear on.
403 * The information returned here is processed by the
404 * {@link blocks_name_allowed_in_format()} function. Look there if you need
405 * to know exactly how this works.
407 * Default case: everything except mod and tag.
409 * @return array page-type prefix => true/false.
411 function applicable_formats() {
412 // Default case: the block can be used in courses and site index, but not in activities
413 return array('all' => true, 'mod' => false, 'tag' => false);
418 * Default return is false - header will be shown
419 * @return boolean
421 function hide_header() {
422 return false;
426 * Return any HTML attributes that you want added to the outer <div> that
427 * of the block when it is output.
429 * Because of the way certain JS events are wired it is a good idea to ensure
430 * that the default values here still get set.
431 * I found the easiest way to do this and still set anything you want is to
432 * override it within your block in the following way
434 * <code php>
435 * function html_attributes() {
436 * $attributes = parent::html_attributes();
437 * $attributes['class'] .= ' mynewclass';
438 * return $attributes;
440 * </code>
442 * @return array attribute name => value.
444 function html_attributes() {
445 $attributes = array(
446 'id' => 'inst' . $this->instance->id,
447 'class' => 'block_' . $this->name() . ' block',
448 'role' => $this->get_aria_role()
450 if ($this->hide_header()) {
451 $attributes['class'] .= ' no-header';
453 if ($this->instance_can_be_docked() && get_user_preferences('docked_block_instance_' . $this->instance->id, 0)) {
454 $attributes['class'] .= ' dock_on_load';
456 return $attributes;
460 * Set up a particular instance of this class given data from the block_insances
461 * table and the current page. (See {@link block_manager::load_blocks()}.)
463 * @param stdClass $instance data from block_insances, block_positions, etc.
464 * @param moodle_page $the page this block is on.
466 function _load_instance($instance, $page) {
467 if (!empty($instance->configdata)) {
468 $this->config = unserialize(base64_decode($instance->configdata));
470 $this->instance = $instance;
471 $this->context = context_block::instance($instance->id);
472 $this->page = $page;
473 $this->specialization();
477 * Allows the block to load any JS it requires into the page.
479 * By default this function simply permits the user to dock the block if it is dockable.
481 * Left null as of MDL-64506.
483 function get_required_javascript() {
487 * This function is called on your subclass right after an instance is loaded
488 * Use this function to act on instance data just after it's loaded and before anything else is done
489 * For instance: if your block will have different title's depending on location (site, course, blog, etc)
491 function specialization() {
492 // Just to make sure that this method exists.
496 * Is each block of this type going to have instance-specific configuration?
497 * Normally, this setting is controlled by {@link instance_allow_multiple()}: if multiple
498 * instances are allowed, then each will surely need its own configuration. However, in some
499 * cases it may be necessary to provide instance configuration to blocks that do not want to
500 * allow multiple instances. In that case, make this function return true.
501 * I stress again that this makes a difference ONLY if {@link instance_allow_multiple()} returns false.
502 * @return boolean
504 function instance_allow_config() {
505 return false;
509 * Are you going to allow multiple instances of each block?
510 * If yes, then it is assumed that the block WILL USE per-instance configuration
511 * @return boolean
513 function instance_allow_multiple() {
514 // Are you going to allow multiple instances of each block?
515 // If yes, then it is assumed that the block WILL USE per-instance configuration
516 return false;
520 * Serialize and store config data
522 function instance_config_save($data, $nolongerused = false) {
523 global $DB;
524 $DB->update_record('block_instances', ['id' => $this->instance->id,
525 'configdata' => base64_encode(serialize($data)), 'timemodified' => time()]);
529 * Replace the instance's configuration data with those currently in $this->config;
531 function instance_config_commit($nolongerused = false) {
532 global $DB;
533 $this->instance_config_save($this->config);
537 * Do any additional initialization you may need at the time a new block instance is created
538 * @return boolean
540 function instance_create() {
541 return true;
545 * Copy any block-specific data when copying to a new block instance.
546 * @param int $fromid the id number of the block instance to copy from
547 * @return boolean
549 public function instance_copy($fromid) {
550 return true;
554 * Delete everything related to this instance if you have been using persistent storage other than the configdata field.
555 * @return boolean
557 function instance_delete() {
558 return true;
562 * Allows the block class to have a say in the user's ability to edit (i.e., configure) blocks of this type.
563 * The framework has first say in whether this will be allowed (e.g., no editing allowed unless in edit mode)
564 * but if the framework does allow it, the block can still decide to refuse.
565 * @return boolean
567 function user_can_edit() {
568 global $USER;
570 if (has_capability('moodle/block:edit', $this->context)) {
571 return true;
574 // The blocks in My Moodle are a special case. We want them to inherit from the user context.
575 if (!empty($USER->id)
576 && $this->instance->parentcontextid == $this->page->context->id // Block belongs to this page
577 && $this->page->context->contextlevel == CONTEXT_USER // Page belongs to a user
578 && $this->page->context->instanceid == $USER->id) { // Page belongs to this user
579 return has_capability('moodle/my:manageblocks', $this->page->context);
582 return false;
586 * Allows the block class to have a say in the user's ability to create new instances of this block.
587 * The framework has first say in whether this will be allowed (e.g., no adding allowed unless in edit mode)
588 * but if the framework does allow it, the block can still decide to refuse.
589 * This function has access to the complete page object, the creation related to which is being determined.
591 * @param moodle_page $page
592 * @return boolean
594 function user_can_addto($page) {
595 // List of formats this block supports.
596 $formats = $this->applicable_formats();
598 // The blocks in My Moodle are a special case and use a different capability.
599 $mypagetypes = my_page_type_list($page->pagetype); // Get list of possible my page types.
601 if (array_key_exists($page->pagetype, $mypagetypes)) { // Ensure we are on a page with a my page type.
602 // If the block cannot be displayed on /my it is ok if the myaddinstance capability is not defined.
603 // Is 'my' explicitly forbidden?
604 // If 'all' has not been allowed, has 'my' been explicitly allowed?
605 if ((isset($formats['my']) && $formats['my'] == false)
606 || (empty($formats['all']) && empty($formats['my']))) {
608 // Block cannot be added to /my regardless of capabilities.
609 return false;
610 } else {
611 $capability = 'block/' . $this->name() . ':myaddinstance';
612 return $this->has_add_block_capability($page, $capability)
613 && has_capability('moodle/my:manageblocks', $page->context);
616 // Check if this is a block only used on /my.
617 unset($formats['my']);
618 if (empty($formats)) {
619 // Block can only be added to /my - return false.
620 return false;
623 $capability = 'block/' . $this->name() . ':addinstance';
624 if ($this->has_add_block_capability($page, $capability)
625 && has_capability('moodle/block:edit', $page->context)) {
626 return true;
629 return false;
633 * Returns true if the user can add a block to a page.
635 * @param moodle_page $page
636 * @param string $capability the capability to check
637 * @return boolean true if user can add a block, false otherwise.
639 private function has_add_block_capability($page, $capability) {
640 // Check if the capability exists.
641 if (!get_capability_info($capability)) {
642 // Debug warning that the capability does not exist, but no more than once per page.
643 static $warned = array();
644 if (!isset($warned[$this->name()])) {
645 debugging('The block ' .$this->name() . ' does not define the standard capability ' .
646 $capability , DEBUG_DEVELOPER);
647 $warned[$this->name()] = 1;
649 // If the capability does not exist, the block can always be added.
650 return true;
651 } else {
652 return has_capability($capability, $page->context);
656 static function get_extra_capabilities() {
657 return array('moodle/block:view', 'moodle/block:edit');
661 * Can be overridden by the block to prevent the block from being dockable.
663 * @return bool
665 * Return false as per MDL-64506
667 public function instance_can_be_docked() {
668 return false;
672 * If overridden and set to false by the block it will not be hidable when
673 * editing is turned on.
675 * @return bool
677 public function instance_can_be_hidden() {
678 return true;
682 * If overridden and set to false by the block it will not be collapsible.
684 * @return bool
686 public function instance_can_be_collapsed() {
687 return true;
690 /** @callback callback functions for comments api */
691 public static function comment_template($options) {
692 $ret = <<<EOD
693 <div class="comment-userpicture">___picture___</div>
694 <div class="comment-content">
695 ___name___ - <span>___time___</span>
696 <div>___content___</div>
697 </div>
698 EOD;
699 return $ret;
701 public static function comment_permissions($options) {
702 return array('view'=>true, 'post'=>true);
704 public static function comment_url($options) {
705 return null;
707 public static function comment_display($comments, $options) {
708 return $comments;
710 public static function comment_add(&$comments, $options) {
711 return true;
715 * Returns the aria role attribute that best describes this block.
717 * Region is the default, but this should be overridden by a block is there is a region child, or even better
718 * a landmark child.
720 * Options are as follows:
721 * - landmark
722 * - application
723 * - banner
724 * - complementary
725 * - contentinfo
726 * - form
727 * - main
728 * - navigation
729 * - search
731 * @return string
733 public function get_aria_role() {
734 return 'complementary';
739 * Specialized class for displaying a block with a list of icons/text labels
741 * The get_content method should set $this->content->items and (optionally)
742 * $this->content->icons, instead of $this->content->text.
744 * @author Jon Papaioannou
745 * @package core_block
748 class block_list extends block_base {
749 var $content_type = BLOCK_TYPE_LIST;
751 function is_empty() {
752 if ( !has_capability('moodle/block:view', $this->context) ) {
753 return true;
756 $this->get_content();
757 return (empty($this->content->items) && empty($this->content->footer));
760 protected function formatted_contents($output) {
761 $this->get_content();
762 $this->get_required_javascript();
763 if (!empty($this->content->items)) {
764 return $output->list_block_contents($this->content->icons, $this->content->items);
765 } else {
766 return '';
770 function html_attributes() {
771 $attributes = parent::html_attributes();
772 $attributes['class'] .= ' list_block';
773 return $attributes;
779 * Specialized class for displaying a tree menu.
781 * The {@link get_content()} method involves setting the content of
782 * <code>$this->content->items</code> with an array of {@link tree_item}
783 * objects (these are the top-level nodes). The {@link tree_item::children}
784 * property may contain more tree_item objects, and so on. The tree_item class
785 * itself is abstract and not intended for use, use one of it's subclasses.
787 * Unlike {@link block_list}, the icons are specified as part of the items,
788 * not in a separate array.
790 * @author Alan Trick
791 * @package core_block
792 * @internal this extends block_list so we get is_empty() for free
794 class block_tree extends block_list {
797 * @var int specifies the manner in which contents should be added to this
798 * block type. In this case <code>$this->content->items</code> is used with
799 * {@link tree_item}s.
801 public $content_type = BLOCK_TYPE_TREE;
804 * Make the formatted HTML ouput.
806 * Also adds the required javascript call to the page output.
808 * @param core_renderer $output
809 * @return string HTML
811 protected function formatted_contents($output) {
812 // based of code in admin_tree
813 global $PAGE; // TODO change this when there is a proper way for blocks to get stuff into head.
814 static $eventattached;
815 if ($eventattached===null) {
816 $eventattached = true;
818 if (!$this->content) {
819 $this->content = new stdClass;
820 $this->content->items = array();
822 $this->get_required_javascript();
823 $this->get_content();
824 $content = $output->tree_block_contents($this->content->items,array('class'=>'block_tree list'));
825 if (isset($this->id) && !is_numeric($this->id)) {
826 $content = $output->box($content, 'block_tree_box', $this->id);
828 return $content;