Merge branch 'MDL-41152-26' of git://github.com/FMCorz/moodle into MOODLE_26_STABLE
[moodle.git] / blocks / moodleblock.class.php
blob461baf15972d4c8ea16b256736231bbb44857620
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This file contains the parent class for moodle blocks, block_base.
21 * @package core
22 * @subpackage block
23 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
26 /// Constants
28 /**
29 * 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.
31 define('BLOCK_TYPE_LIST', 1);
33 /**
34 * 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.
36 define('BLOCK_TYPE_TEXT', 2);
37 /**
38 * Block type of tree. $this->content->items is a list of tree_item objects and $this->content->footer is a string.
40 define('BLOCK_TYPE_TREE', 3);
42 /**
43 * Class for describing a moodle block, all Moodle blocks derive from this class
45 * @author Jon Papaioannou
46 * @package blocks
48 class block_base {
50 /**
51 * Internal var for storing/caching translated strings
52 * @var string $str
54 var $str;
56 /**
57 * The title of the block to be displayed in the block title area.
58 * @var string $title
60 var $title = NULL;
62 /**
63 * The name of the block to be displayed in the block title area if the title is empty.
64 * @var string arialabel
66 var $arialabel = NULL;
68 /**
69 * The type of content that this block creates. Currently support options - BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT
70 * @var int $content_type
72 var $content_type = BLOCK_TYPE_TEXT;
74 /**
75 * An object to contain the information to be displayed in the block.
76 * @var stdObject $content
78 var $content = NULL;
80 /**
81 * A string generated by {@link _add_edit_controls()} to display block manipulation links when the user is in editing mode.
82 * @var string $edit_controls
84 var $edit_controls = NULL;
86 /**
87 * The initialized instance of this block object.
88 * @var block $instance
90 var $instance = NULL;
92 /**
93 * The page that this block is appearing on.
94 * @var moodle_page
96 public $page = NULL;
98 /**
99 * This blocks's context.
100 * @var stdClass
102 public $context = NULL;
105 * An object containing the instance configuration information for the current instance of this block.
106 * @var stdObject $config
108 var $config = NULL;
111 * How often the cronjob should run, 0 if not at all.
112 * @var int $cron
115 var $cron = NULL;
117 /// Class Functions
120 * Fake constructor to keep PHP5 happy
123 function __construct() {
124 $this->init();
128 * Function that can be overridden to do extra cleanup before
129 * the database tables are deleted. (Called once per block, not per instance!)
131 function before_delete() {
135 * Returns the block name, as present in the class name,
136 * the database, the block directory, etc etc.
138 * @return string
140 function name() {
141 // Returns the block name, as present in the class name,
142 // the database, the block directory, etc etc.
143 static $myname;
144 if ($myname === NULL) {
145 $myname = strtolower(get_class($this));
146 $myname = substr($myname, strpos($myname, '_') + 1);
148 return $myname;
152 * Parent class version of this function simply returns NULL
153 * This should be implemented by the derived class to return
154 * the content object.
156 * @return stdObject
158 function get_content() {
159 // This should be implemented by the derived class.
160 return NULL;
164 * Returns the class $title var value.
166 * Intentionally doesn't check if a title is set.
167 * This is already done in {@link _self_test()}
169 * @return string $this->title
171 function get_title() {
172 // Intentionally doesn't check if a title is set. This is already done in _self_test()
173 return $this->title;
177 * Returns the class $content_type var value.
179 * Intentionally doesn't check if content_type is set.
180 * This is already done in {@link _self_test()}
182 * @return string $this->content_type
184 function get_content_type() {
185 // Intentionally doesn't check if a content_type is set. This is already done in _self_test()
186 return $this->content_type;
190 * Returns true or false, depending on whether this block has any content to display
191 * and whether the user has permission to view the block
193 * @return boolean
195 function is_empty() {
196 if ( !has_capability('moodle/block:view', $this->context) ) {
197 return true;
200 $this->get_content();
201 return(empty($this->content->text) && empty($this->content->footer));
205 * First sets the current value of $this->content to NULL
206 * then calls the block's {@link get_content()} function
207 * to set its value back.
209 * @return stdObject
211 function refresh_content() {
212 // Nothing special here, depends on content()
213 $this->content = NULL;
214 return $this->get_content();
218 * Return a block_contents object representing the full contents of this block.
220 * This internally calls ->get_content(), and then adds the editing controls etc.
222 * You probably should not override this method, but instead override
223 * {@link html_attributes()}, {@link formatted_contents()} or {@link get_content()},
224 * {@link hide_header()}, {@link (get_edit_controls)}, etc.
226 * @return block_contents a representation of the block, for rendering.
227 * @since Moodle 2.0.
229 public function get_content_for_output($output) {
230 global $CFG;
232 $bc = new block_contents($this->html_attributes());
233 $bc->attributes['data-block'] = $this->name();
234 $bc->blockinstanceid = $this->instance->id;
235 $bc->blockpositionid = $this->instance->blockpositionid;
237 if ($this->instance->visible) {
238 $bc->content = $this->formatted_contents($output);
239 if (!empty($this->content->footer)) {
240 $bc->footer = $this->content->footer;
242 } else {
243 $bc->add_class('invisible');
246 if (!$this->hide_header()) {
247 $bc->title = $this->title;
250 if (empty($bc->title)) {
251 $bc->arialabel = new lang_string('pluginname', get_class($this));
252 $this->arialabel = $bc->arialabel;
255 if ($this->page->user_is_editing()) {
256 $bc->controls = $this->page->blocks->edit_controls($this);
257 } else {
258 // we must not use is_empty on hidden blocks
259 if ($this->is_empty() && !$bc->controls) {
260 return null;
264 if (empty($CFG->allowuserblockhiding)
265 || (empty($bc->content) && empty($bc->footer))
266 || !$this->instance_can_be_collapsed()) {
267 $bc->collapsible = block_contents::NOT_HIDEABLE;
268 } else if (get_user_preferences('block' . $bc->blockinstanceid . 'hidden', false)) {
269 $bc->collapsible = block_contents::HIDDEN;
270 } else {
271 $bc->collapsible = block_contents::VISIBLE;
274 if ($this->instance_can_be_docked() && !$this->hide_header()) {
275 $bc->dockable = true;
278 $bc->annotation = ''; // TODO MDL-19398 need to work out what to say here.
280 return $bc;
284 * Convert the contents of the block to HTML.
286 * This is used by block base classes like block_list to convert the structured
287 * $this->content->list and $this->content->icons arrays to HTML. So, in most
288 * blocks, you probaby want to override the {@link get_contents()} method,
289 * which generates that structured representation of the contents.
291 * @param $output The core_renderer to use when generating the output.
292 * @return string the HTML that should appearn in the body of the block.
293 * @since Moodle 2.0.
295 protected function formatted_contents($output) {
296 $this->get_content();
297 $this->get_required_javascript();
298 if (!empty($this->content->text)) {
299 return $this->content->text;
300 } else {
301 return '';
306 * Tests if this block has been implemented correctly.
307 * Also, $errors isn't used right now
309 * @return boolean
312 function _self_test() {
313 // Tests if this block has been implemented correctly.
314 // Also, $errors isn't used right now
315 $errors = array();
317 $correct = true;
318 if ($this->get_title() === NULL) {
319 $errors[] = 'title_not_set';
320 $correct = false;
322 if (!in_array($this->get_content_type(), array(BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT, BLOCK_TYPE_TREE))) {
323 $errors[] = 'invalid_content_type';
324 $correct = false;
326 //following selftest was not working when roles&capabilities were used from block
327 /* if ($this->get_content() === NULL) {
328 $errors[] = 'content_not_set';
329 $correct = false;
331 $formats = $this->applicable_formats();
332 if (empty($formats) || array_sum($formats) === 0) {
333 $errors[] = 'no_formats';
334 $correct = false;
337 $width = $this->preferred_width();
338 if (!is_int($width) || $width <= 0) {
339 $errors[] = 'invalid_width';
340 $correct = false;
342 return $correct;
346 * Subclasses should override this and return true if the
347 * subclass block has a settings.php file.
349 * @return boolean
351 function has_config() {
352 return false;
356 * Default behavior: save all variables as $CFG properties
357 * You don't need to override this if you 're satisfied with the above
359 * @param array $data
360 * @return boolean
362 function config_save($data) {
363 foreach ($data as $name => $value) {
364 set_config($name, $value);
366 return true;
370 * Which page types this block may appear on.
372 * The information returned here is processed by the
373 * {@link blocks_name_allowed_in_format()} function. Look there if you need
374 * to know exactly how this works.
376 * Default case: everything except mod and tag.
378 * @return array page-type prefix => true/false.
380 function applicable_formats() {
381 // Default case: the block can be used in courses and site index, but not in activities
382 return array('all' => true, 'mod' => false, 'tag' => false);
387 * Default return is false - header will be shown
388 * @return boolean
390 function hide_header() {
391 return false;
395 * Return any HTML attributes that you want added to the outer <div> that
396 * of the block when it is output.
398 * Because of the way certain JS events are wired it is a good idea to ensure
399 * that the default values here still get set.
400 * I found the easiest way to do this and still set anything you want is to
401 * override it within your block in the following way
403 * <code php>
404 * function html_attributes() {
405 * $attributes = parent::html_attributes();
406 * $attributes['class'] .= ' mynewclass';
407 * return $attributes;
409 * </code>
411 * @return array attribute name => value.
413 function html_attributes() {
414 $attributes = array(
415 'id' => 'inst' . $this->instance->id,
416 'class' => 'block_' . $this->name(). ' block',
417 'role' => $this->get_aria_role()
419 if ($this->hide_header()) {
420 $attributes['class'] .= ' no-header';
422 if ($this->instance_can_be_docked() && get_user_preferences('docked_block_instance_'.$this->instance->id, 0)) {
423 $attributes['class'] .= ' dock_on_load';
425 return $attributes;
429 * Set up a particular instance of this class given data from the block_insances
430 * table and the current page. (See {@link block_manager::load_blocks()}.)
432 * @param stdClass $instance data from block_insances, block_positions, etc.
433 * @param moodle_page $the page this block is on.
435 function _load_instance($instance, $page) {
436 if (!empty($instance->configdata)) {
437 $this->config = unserialize(base64_decode($instance->configdata));
439 $this->instance = $instance;
440 $this->context = context_block::instance($instance->id);
441 $this->page = $page;
442 $this->specialization();
446 * Allows the block to load any JS it requires into the page.
448 * By default this function simply permits the user to dock the block if it is dockable.
450 function get_required_javascript() {
451 if ($this->instance_can_be_docked() && !$this->hide_header()) {
452 user_preference_allow_ajax_update('docked_block_instance_'.$this->instance->id, PARAM_INT);
457 * This function is called on your subclass right after an instance is loaded
458 * Use this function to act on instance data just after it's loaded and before anything else is done
459 * For instance: if your block will have different title's depending on location (site, course, blog, etc)
461 function specialization() {
462 // Just to make sure that this method exists.
466 * Is each block of this type going to have instance-specific configuration?
467 * Normally, this setting is controlled by {@link instance_allow_multiple()}: if multiple
468 * instances are allowed, then each will surely need its own configuration. However, in some
469 * cases it may be necessary to provide instance configuration to blocks that do not want to
470 * allow multiple instances. In that case, make this function return true.
471 * I stress again that this makes a difference ONLY if {@link instance_allow_multiple()} returns false.
472 * @return boolean
474 function instance_allow_config() {
475 return false;
479 * Are you going to allow multiple instances of each block?
480 * If yes, then it is assumed that the block WILL USE per-instance configuration
481 * @return boolean
483 function instance_allow_multiple() {
484 // Are you going to allow multiple instances of each block?
485 // If yes, then it is assumed that the block WILL USE per-instance configuration
486 return false;
490 * Default behavior: print the config_instance.html file
491 * You don't need to override this if you're satisfied with the above
493 * @deprecated since Moodle 2.0.
494 * @return boolean whether anything was done. Blocks should use edit_form.php.
496 function instance_config_print() {
497 global $CFG, $DB, $OUTPUT;
498 // Default behavior: print the config_instance.html file
499 // You don't need to override this if you're satisfied with the above
500 if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
501 return false;
504 if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
505 echo $OUTPUT->box_start('generalbox boxaligncenter blockconfiginstance');
506 include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
507 echo $OUTPUT->box_end();
508 } else {
509 notice(get_string('blockconfigbad'), str_replace('blockaction=', 'dummy=', qualified_me()));
512 return true;
516 * Serialize and store config data
518 function instance_config_save($data, $nolongerused = false) {
519 global $DB;
520 $DB->set_field('block_instances', 'configdata', base64_encode(serialize($data)),
521 array('id' => $this->instance->id));
525 * Replace the instance's configuration data with those currently in $this->config;
527 function instance_config_commit($nolongerused = false) {
528 global $DB;
529 $this->instance_config_save($this->config);
533 * Do any additional initialization you may need at the time a new block instance is created
534 * @return boolean
536 function instance_create() {
537 return true;
541 * Delete everything related to this instance if you have been using persistent storage other than the configdata field.
542 * @return boolean
544 function instance_delete() {
545 return true;
549 * Allows the block class to have a say in the user's ability to edit (i.e., configure) blocks of this type.
550 * The framework has first say in whether this will be allowed (e.g., no editing allowed unless in edit mode)
551 * but if the framework does allow it, the block can still decide to refuse.
552 * @return boolean
554 function user_can_edit() {
555 global $USER;
557 if (has_capability('moodle/block:edit', $this->context)) {
558 return true;
561 // The blocks in My Moodle are a special case. We want them to inherit from the user context.
562 if (!empty($USER->id)
563 && $this->instance->parentcontextid == $this->page->context->id // Block belongs to this page
564 && $this->page->context->contextlevel == CONTEXT_USER // Page belongs to a user
565 && $this->page->context->instanceid == $USER->id) { // Page belongs to this user
566 return has_capability('moodle/my:manageblocks', $this->page->context);
569 return false;
573 * Allows the block class to have a say in the user's ability to create new instances of this block.
574 * The framework has first say in whether this will be allowed (e.g., no adding allowed unless in edit mode)
575 * but if the framework does allow it, the block can still decide to refuse.
576 * This function has access to the complete page object, the creation related to which is being determined.
578 * @param moodle_page $page
579 * @return boolean
581 function user_can_addto($page) {
582 global $USER;
584 // The blocks in My Moodle are a special case and use a different capability.
585 if (!empty($USER->id)
586 && $page->context->contextlevel == CONTEXT_USER // Page belongs to a user
587 && $page->context->instanceid == $USER->id // Page belongs to this user
588 && $page->pagetype == 'my-index') { // Ensure we are on the My Moodle page
589 $capability = 'block/' . $this->name() . ':myaddinstance';
590 return $this->has_add_block_capability($page, $capability)
591 && has_capability('moodle/my:manageblocks', $page->context);
594 $capability = 'block/' . $this->name() . ':addinstance';
595 if ($this->has_add_block_capability($page, $capability)
596 && has_capability('moodle/block:edit', $page->context)) {
597 return true;
600 return false;
604 * Returns true if the user can add a block to a page.
606 * @param moodle_page $page
607 * @param string $capability the capability to check
608 * @return boolean true if user can add a block, false otherwise.
610 private function has_add_block_capability($page, $capability) {
611 // Check if the capability exists.
612 if (!get_capability_info($capability)) {
613 // Debug warning that the capability does not exist, but no more than once per page.
614 static $warned = array();
615 if (!isset($warned[$this->name()])) {
616 debugging('The block ' .$this->name() . ' does not define the standard capability ' .
617 $capability , DEBUG_DEVELOPER);
618 $warned[$this->name()] = 1;
620 // If the capability does not exist, the block can always be added.
621 return true;
622 } else {
623 return has_capability($capability, $page->context);
627 static function get_extra_capabilities() {
628 return array('moodle/block:view', 'moodle/block:edit');
631 // Methods deprecated in Moodle 2.0 ========================================
634 * Default case: the block wants to be 180 pixels wide
635 * @deprecated since Moodle 2.0.
636 * @return int
638 function preferred_width() {
639 return 180;
642 /** @deprecated since Moodle 2.0. */
643 function _print_block() {
644 throw new coding_exception('_print_block is no longer used. It was a private ' .
645 'method of the block class, only for use by the blocks system. You ' .
646 'should not have been calling it anyway.');
649 /** @deprecated since Moodle 2.0. */
650 function _print_shadow() {
651 throw new coding_exception('_print_shadow is no longer used. It was a private ' .
652 'method of the block class, only for use by the blocks system. You ' .
653 'should not have been calling it anyway.');
656 /** @deprecated since Moodle 2.0. */
657 function _title_html() {
658 throw new coding_exception('_title_html is no longer used. It was a private ' .
659 'method of the block class, only for use by the blocks system. You ' .
660 'should not have been calling it anyway.');
663 /** @deprecated since Moodle 2.0. */
664 function _add_edit_controls() {
665 throw new coding_exception('_add_edit_controls is no longer used. It was a private ' .
666 'method of the block class, only for use by the blocks system. You ' .
667 'should not have been calling it anyway.');
670 /** @deprecated since Moodle 2.0. */
671 function config_print() {
672 throw new coding_exception('config_print() can no longer be used. Blocks should use a settings.php file.');
676 * Can be overridden by the block to prevent the block from being dockable.
678 * @return bool
680 public function instance_can_be_docked() {
681 global $CFG;
682 return (!empty($CFG->allowblockstodock) && $this->page->theme->enable_dock);
686 * If overridden and set to false by the block it will not be hidable when
687 * editing is turned on.
689 * @return bool
691 public function instance_can_be_hidden() {
692 return true;
696 * If overridden and set to false by the block it will not be collapsible.
698 * @return bool
700 public function instance_can_be_collapsed() {
701 return true;
704 /** @callback callback functions for comments api */
705 public static function comment_template($options) {
706 $ret = <<<EOD
707 <div class="comment-userpicture">___picture___</div>
708 <div class="comment-content">
709 ___name___ - <span>___time___</span>
710 <div>___content___</div>
711 </div>
712 EOD;
713 return $ret;
715 public static function comment_permissions($options) {
716 return array('view'=>true, 'post'=>true);
718 public static function comment_url($options) {
719 return null;
721 public static function comment_display($comments, $options) {
722 return $comments;
724 public static function comment_add(&$comments, $options) {
725 return true;
729 * Returns the aria role attribute that best describes this block.
731 * Region is the default, but this should be overridden by a block is there is a region child, or even better
732 * a landmark child.
734 * Options are as follows:
735 * - landmark
736 * - application
737 * - banner
738 * - complementary
739 * - contentinfo
740 * - form
741 * - main
742 * - navigation
743 * - search
745 * @return string
747 public function get_aria_role() {
748 return 'complementary';
753 * Specialized class for displaying a block with a list of icons/text labels
755 * The get_content method should set $this->content->items and (optionally)
756 * $this->content->icons, instead of $this->content->text.
758 * @author Jon Papaioannou
759 * @package blocks
762 class block_list extends block_base {
763 var $content_type = BLOCK_TYPE_LIST;
765 function is_empty() {
766 if ( !has_capability('moodle/block:view', $this->context) ) {
767 return true;
770 $this->get_content();
771 return (empty($this->content->items) && empty($this->content->footer));
774 protected function formatted_contents($output) {
775 $this->get_content();
776 $this->get_required_javascript();
777 if (!empty($this->content->items)) {
778 return $output->list_block_contents($this->content->icons, $this->content->items);
779 } else {
780 return '';
784 function html_attributes() {
785 $attributes = parent::html_attributes();
786 $attributes['class'] .= ' list_block';
787 return $attributes;
793 * Specialized class for displaying a tree menu.
795 * The {@link get_content()} method involves setting the content of
796 * <code>$this->content->items</code> with an array of {@link tree_item}
797 * objects (these are the top-level nodes). The {@link tree_item::children}
798 * property may contain more tree_item objects, and so on. The tree_item class
799 * itself is abstract and not intended for use, use one of it's subclasses.
801 * Unlike {@link block_list}, the icons are specified as part of the items,
802 * not in a separate array.
804 * @author Alan Trick
805 * @package blocks
806 * @internal this extends block_list so we get is_empty() for free
808 class block_tree extends block_list {
811 * @var int specifies the manner in which contents should be added to this
812 * block type. In this case <code>$this->content->items</code> is used with
813 * {@link tree_item}s.
815 public $content_type = BLOCK_TYPE_TREE;
818 * Make the formatted HTML ouput.
820 * Also adds the required javascript call to the page output.
822 * @param core_renderer $output
823 * @return string HTML
825 protected function formatted_contents($output) {
826 // based of code in admin_tree
827 global $PAGE; // TODO change this when there is a proper way for blocks to get stuff into head.
828 static $eventattached;
829 if ($eventattached===null) {
830 $eventattached = true;
832 if (!$this->content) {
833 $this->content = new stdClass;
834 $this->content->items = array();
836 $this->get_required_javascript();
837 $this->get_content();
838 $content = $output->tree_block_contents($this->content->items,array('class'=>'block_tree list'));
839 if (isset($this->id) && !is_numeric($this->id)) {
840 $content = $output->box($content, 'block_tree_box', $this->id);
842 return $content;