Automatic installer lang files (20101106)
[moodle.git] / blocks / moodleblock.class.php
blobab2e9dabe28579d8cbb4a048995fdda8eb0827de
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 type of content that this block creates. Currently support options - BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT
64 * @var int $content_type
66 var $content_type = BLOCK_TYPE_TEXT;
68 /**
69 * An object to contain the information to be displayed in the block.
70 * @var stdObject $content
72 var $content = NULL;
74 /**
75 * A string generated by {@link _add_edit_controls()} to display block manipulation links when the user is in editing mode.
76 * @var string $edit_controls
78 var $edit_controls = NULL;
80 /**
81 * The initialized instance of this block object.
82 * @var block $instance
84 var $instance = NULL;
86 /**
87 * The page that this block is appearing on.
88 * @var moodle_page
90 public $page = NULL;
92 /**
93 * This blocks's context.
94 * @var stdClass
96 public $context = NULL;
98 /**
99 * An object containing the instance configuration information for the current instance of this block.
100 * @var stdObject $config
102 var $config = NULL;
105 * How often the cronjob should run, 0 if not at all.
106 * @var int $cron
109 var $cron = NULL;
111 /// Class Functions
114 * Fake constructor to keep PHP5 happy
117 function __construct() {
118 $this->init();
122 * Function that can be overridden to do extra cleanup before
123 * the database tables are deleted. (Called once per block, not per instance!)
125 function before_delete() {
129 * Returns the block name, as present in the class name,
130 * the database, the block directory, etc etc.
132 * @return string
134 function name() {
135 // Returns the block name, as present in the class name,
136 // the database, the block directory, etc etc.
137 static $myname;
138 if ($myname === NULL) {
139 $myname = strtolower(get_class($this));
140 $myname = substr($myname, strpos($myname, '_') + 1);
142 return $myname;
146 * Parent class version of this function simply returns NULL
147 * This should be implemented by the derived class to return
148 * the content object.
150 * @return stdObject
152 function get_content() {
153 // This should be implemented by the derived class.
154 return NULL;
158 * Returns the class $title var value.
160 * Intentionally doesn't check if a title is set.
161 * This is already done in {@link _self_test()}
163 * @return string $this->title
165 function get_title() {
166 // Intentionally doesn't check if a title is set. This is already done in _self_test()
167 return $this->title;
171 * Returns the class $content_type var value.
173 * Intentionally doesn't check if content_type is set.
174 * This is already done in {@link _self_test()}
176 * @return string $this->content_type
178 function get_content_type() {
179 // Intentionally doesn't check if a content_type is set. This is already done in _self_test()
180 return $this->content_type;
184 * Returns true or false, depending on whether this block has any content to display
185 * and whether the user has permission to view the block
187 * @return boolean
189 function is_empty() {
190 if ( !has_capability('moodle/block:view', $this->context) ) {
191 return true;
194 $this->get_content();
195 return(empty($this->content->text) && empty($this->content->footer));
199 * First sets the current value of $this->content to NULL
200 * then calls the block's {@link get_content()} function
201 * to set its value back.
203 * @return stdObject
205 function refresh_content() {
206 // Nothing special here, depends on content()
207 $this->content = NULL;
208 return $this->get_content();
212 * Return a block_contents oject representing the full contents of this block.
214 * This internally calls ->get_content(), and then adds the editing controls etc.
216 * You probably should not override this method, but instead override
217 * {@link html_attributes()}, {@link formatted_contents()} or {@link get_content()},
218 * {@link hide_header()}, {@link (get_edit_controls)}, etc.
220 * @return block_contents a represntation of the block, for rendering.
221 * @since Moodle 2.0.
223 public function get_content_for_output($output) {
224 global $CFG;
226 $bc = new block_contents($this->html_attributes());
228 $bc->blockinstanceid = $this->instance->id;
229 $bc->blockpositionid = $this->instance->blockpositionid;
231 if ($this->instance->visible) {
232 $bc->content = $this->formatted_contents($output);
233 if (!empty($this->content->footer)) {
234 $bc->footer = $this->content->footer;
236 } else {
237 $bc->add_class('invisible');
240 if (!$this->hide_header()) {
241 $bc->title = $this->title;
244 if ($this->page->user_is_editing()) {
245 $bc->controls = $this->page->blocks->edit_controls($this);
248 if ($this->is_empty() && !$bc->controls) {
249 return null;
252 if (empty($CFG->allowuserblockhiding) ||
253 (empty($bc->content) && empty($bc->footer))) {
254 $bc->collapsible = block_contents::NOT_HIDEABLE;
255 } else if (get_user_preferences('block' . $bc->blockinstanceid . 'hidden', false)) {
256 $bc->collapsible = block_contents::HIDDEN;
257 } else {
258 $bc->collapsible = block_contents::VISIBLE;
261 $bc->annotation = ''; // TODO MDL-19398 need to work out what to say here.
263 return $bc;
267 * Convert the contents of the block to HTML.
269 * This is used by block base classes like block_list to convert the structured
270 * $this->content->list and $this->content->icons arrays to HTML. So, in most
271 * blocks, you probaby want to override the {@link get_contents()} method,
272 * which generates that structured representation of the contents.
274 * @param $output The core_renderer to use when generating the output.
275 * @return string the HTML that should appearn in the body of the block.
276 * @since Moodle 2.0.
278 protected function formatted_contents($output) {
279 $this->get_content();
280 if (!empty($this->content->text)) {
281 $this->get_required_javascript();
282 return $this->content->text;
283 } else {
284 return '';
289 * Tests if this block has been implemented correctly.
290 * Also, $errors isn't used right now
292 * @return boolean
295 function _self_test() {
296 // Tests if this block has been implemented correctly.
297 // Also, $errors isn't used right now
298 $errors = array();
300 $correct = true;
301 if ($this->get_title() === NULL) {
302 $errors[] = 'title_not_set';
303 $correct = false;
305 if (!in_array($this->get_content_type(), array(BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT, BLOCK_TYPE_TREE))) {
306 $errors[] = 'invalid_content_type';
307 $correct = false;
309 //following selftest was not working when roles&capabilities were used from block
310 /* if ($this->get_content() === NULL) {
311 $errors[] = 'content_not_set';
312 $correct = false;
314 $formats = $this->applicable_formats();
315 if (empty($formats) || array_sum($formats) === 0) {
316 $errors[] = 'no_formats';
317 $correct = false;
320 $width = $this->preferred_width();
321 if (!is_int($width) || $width <= 0) {
322 $errors[] = 'invalid_width';
323 $correct = false;
325 return $correct;
329 * Subclasses should override this and return true if the
330 * subclass block has a config_global.html file.
332 * @return boolean
334 function has_config() {
335 return false;
339 * Default behavior: save all variables as $CFG properties
340 * You don't need to override this if you 're satisfied with the above
342 * @param array $data
343 * @return boolean
345 function config_save($data) {
346 foreach ($data as $name => $value) {
347 set_config($name, $value);
349 return true;
353 * Which page types this block may appear on.
355 * The information returned here is processed by the
356 * {@link blocks_name_allowed_in_format()} function. Look there if you need
357 * to know exactly how this works.
359 * Default case: everything except mod and tag.
361 * @return array page-type prefix => true/false.
363 function applicable_formats() {
364 // Default case: the block can be used in courses and site index, but not in activities
365 return array('all' => true, 'mod' => false, 'tag' => false);
370 * Default return is false - header will be shown
371 * @return boolean
373 function hide_header() {
374 return false;
378 * Return any HTML attributes that you want added to the outer <div> that
379 * of the block when it is output.
381 * Because of the way certain JS events are wired it is a good idea to ensure
382 * that the default values here still get set.
383 * I found the easiest way to do this and still set anything you want is to
384 * override it within your block in the following way
386 * <code php>
387 * function html_attributes() {
388 * $attributes = parent::html_attributes();
389 * $attributes['class'] .= ' mynewclass';
390 * return $attributes;
392 * </code>
394 * @return array attribute name => value.
396 function html_attributes() {
397 $attributes = array(
398 'id' => 'inst' . $this->instance->id,
399 'class' => 'block_' . $this->name(). ' block'
401 if ($this->instance_can_be_docked() && get_user_preferences('docked_block_instance_'.$this->instance->id, 0)) {
402 $attributes['class'] .= ' dock_on_load';
404 return $attributes;
408 * Set up a particular instance of this class given data from the block_insances
409 * table and the current page. (See {@link block_manager::load_blocks()}.)
411 * @param stdClass $instance data from block_insances, block_positions, etc.
412 * @param moodle_page $the page this block is on.
414 function _load_instance($instance, $page) {
415 if (!empty($instance->configdata)) {
416 $this->config = unserialize(base64_decode($instance->configdata));
418 $this->instance = $instance;
419 $this->context = get_context_instance(CONTEXT_BLOCK, $instance->id);
420 $this->page = $page;
421 $this->specialization();
424 function get_required_javascript() {
425 if ($this->instance_can_be_docked() && !$this->hide_header()) {
426 $this->page->requires->js_init_call('M.core_dock.init_genericblock', array($this->instance->id));
427 user_preference_allow_ajax_update('docked_block_instance_'.$this->instance->id, PARAM_INT);
432 * This function is called on your subclass right after an instance is loaded
433 * Use this function to act on instance data just after it's loaded and before anything else is done
434 * For instance: if your block will have different title's depending on location (site, course, blog, etc)
436 function specialization() {
437 // Just to make sure that this method exists.
441 * Is each block of this type going to have instance-specific configuration?
442 * Normally, this setting is controlled by {@link instance_allow_multiple()}: if multiple
443 * instances are allowed, then each will surely need its own configuration. However, in some
444 * cases it may be necessary to provide instance configuration to blocks that do not want to
445 * allow multiple instances. In that case, make this function return true.
446 * I stress again that this makes a difference ONLY if {@link instance_allow_multiple()} returns false.
447 * @return boolean
449 function instance_allow_config() {
450 return false;
454 * Are you going to allow multiple instances of each block?
455 * If yes, then it is assumed that the block WILL USE per-instance configuration
456 * @return boolean
458 function instance_allow_multiple() {
459 // Are you going to allow multiple instances of each block?
460 // If yes, then it is assumed that the block WILL USE per-instance configuration
461 return false;
465 * Default behavior: print the config_instance.html file
466 * You don't need to override this if you're satisfied with the above
468 * @deprecated since Moodle 2.0.
469 * @return boolean whether anything was done. Blocks should use edit_form.php.
471 function instance_config_print() {
472 global $CFG, $DB, $OUTPUT;
473 // Default behavior: print the config_instance.html file
474 // You don't need to override this if you're satisfied with the above
475 if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
476 return false;
479 if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
480 echo $OUTPUT->box_start('generalbox boxaligncenter blockconfiginstance');
481 include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
482 echo $OUTPUT->box_end();
483 } else {
484 notice(get_string('blockconfigbad'), str_replace('blockaction=', 'dummy=', qualified_me()));
487 return true;
491 * Serialize and store config data
493 function instance_config_save($data, $nolongerused = false) {
494 global $DB;
495 $DB->set_field('block_instances', 'configdata', base64_encode(serialize($data)),
496 array('id' => $this->instance->id));
500 * Replace the instance's configuration data with those currently in $this->config;
502 function instance_config_commit($nolongerused = false) {
503 global $DB;
504 $this->instance_config_save($this->config);
508 * Do any additional initialization you may need at the time a new block instance is created
509 * @return boolean
511 function instance_create() {
512 return true;
516 * Delete everything related to this instance if you have been using persistent storage other than the configdata field.
517 * @return boolean
519 function instance_delete() {
520 return true;
524 * Allows the block class to have a say in the user's ability to edit (i.e., configure) blocks of this type.
525 * The framework has first say in whether this will be allowed (e.g., no editing allowed unless in edit mode)
526 * but if the framework does allow it, the block can still decide to refuse.
527 * @return boolean
529 function user_can_edit() {
530 global $USER;
532 if (has_capability('moodle/block:edit', $this->context)) {
533 return true;
536 // The blocks in My Moodle are a special case. We want them to inherit from the user context.
537 if (!empty($USER->id)
538 && $this->instance->parentcontextid == $this->page->context->id // Block belongs to this page
539 && $this->page->context->contextlevel == CONTEXT_USER // Page belongs to a user
540 && $this->page->context->instanceid == $USER->id) { // Page belongs to this user
541 return has_capability('moodle/my:manageblocks', $this->page->context);
544 return false;
548 * Allows the block class to have a say in the user's ability to create new instances of this block.
549 * The framework has first say in whether this will be allowed (e.g., no adding allowed unless in edit mode)
550 * but if the framework does allow it, the block can still decide to refuse.
551 * This function has access to the complete page object, the creation related to which is being determined.
553 * @param moodle_page $page
554 * @return boolean
556 function user_can_addto($page) {
557 global $USER;
559 if (has_capability('moodle/block:edit', $page->context)) {
560 return true;
563 // The blocks in My Moodle are a special case and use a different capability.
564 if (!empty($USER->id)
565 && $page->context->contextlevel == CONTEXT_USER // Page belongs to a user
566 && $page->context->instanceid == $USER->id) { // Page belongs to this user
567 return has_capability('moodle/my:manageblocks', $page->context);
570 return false;
573 function get_extra_capabilities() {
574 return array('moodle/block:view', 'moodle/block:edit');
577 // Methods deprecated in Moodle 2.0 ========================================
580 * Default case: the block wants to be 180 pixels wide
581 * @deprecated since Moodle 2.0.
582 * @return int
584 function preferred_width() {
585 return 180;
588 /** @deprecated since Moodle 2.0. */
589 function _print_block() {
590 throw new coding_exception('_print_block is no longer used. It was a private ' .
591 'method of the block class, only for use by the blocks system. You ' .
592 'should not have been calling it anyway.');
595 /** @deprecated since Moodle 2.0. */
596 function _print_shadow() {
597 throw new coding_exception('_print_shadow is no longer used. It was a private ' .
598 'method of the block class, only for use by the blocks system. You ' .
599 'should not have been calling it anyway.');
602 /** @deprecated since Moodle 2.0. */
603 function _title_html() {
604 throw new coding_exception('_title_html is no longer used. It was a private ' .
605 'method of the block class, only for use by the blocks system. You ' .
606 'should not have been calling it anyway.');
609 /** @deprecated since Moodle 2.0. */
610 function _add_edit_controls() {
611 throw new coding_exception('_add_edit_controls is no longer used. It was a private ' .
612 'method of the block class, only for use by the blocks system. You ' .
613 'should not have been calling it anyway.');
616 /** @deprecated since Moodle 2.0. */
617 function config_print() {
618 throw new coding_exception('config_print() can no longer be used. Blocks should use a settings.php file.');
622 * Can be overridden by the block to prevent the block from being dockable.
624 * @return bool
626 public function instance_can_be_docked() {
627 global $CFG;
628 return (!empty($CFG->allowblockstodock) && $this->page->theme->enable_dock);
632 * If overridden and set to true by the block it will not be hidable when
633 * editing is turned on.
635 * @return bool
637 public function instance_can_be_hidden() {
638 return true;
641 /** @callback callback functions for comments api */
642 public static function comment_template($options) {
643 $ret = <<<EOD
644 <div class="comment-userpicture">___picture___</div>
645 <div class="comment-content">
646 ___name___ - <span>___time___</span>
647 <div>___content___</div>
648 </div>
649 EOD;
650 return $ret;
652 public static function comment_permissions($options) {
653 return array('view'=>true, 'post'=>true);
655 public static function comment_url($options) {
656 return null;
658 public static function comment_display($comments, $options) {
659 return $comments;
661 public static function comment_add(&$comments, $options) {
662 return true;
667 * Specialized class for displaying a block with a list of icons/text labels
669 * The get_content method should set $this->content->items and (optionally)
670 * $this->content->icons, instead of $this->content->text.
672 * @author Jon Papaioannou
673 * @package blocks
676 class block_list extends block_base {
677 var $content_type = BLOCK_TYPE_LIST;
679 function is_empty() {
680 if ( !has_capability('moodle/block:view', $this->context) ) {
681 return true;
684 $this->get_content();
685 return (empty($this->content->items) && empty($this->content->footer));
688 protected function formatted_contents($output) {
689 $this->get_content();
690 if (!empty($this->content->items)) {
691 $this->get_required_javascript();
692 return $output->list_block_contents($this->content->icons, $this->content->items);
693 } else {
694 return '';
700 * Specialized class for displaying a tree menu.
702 * The {@link get_content()} method involves setting the content of
703 * <code>$this->content->items</code> with an array of {@link tree_item}
704 * objects (these are the top-level nodes). The {@link tree_item::children}
705 * property may contain more tree_item objects, and so on. The tree_item class
706 * itself is abstract and not intended for use, use one of it's subclasses.
708 * Unlike {@link block_list}, the icons are specified as part of the items,
709 * not in a separate array.
711 * @author Alan Trick
712 * @package blocks
713 * @internal this extends block_list so we get is_empty() for free
715 class block_tree extends block_list {
718 * @var int specifies the manner in which contents should be added to this
719 * block type. In this case <code>$this->content->items</code> is used with
720 * {@link tree_item}s.
722 public $content_type = BLOCK_TYPE_TREE;
725 * Make the formatted HTML ouput.
727 * Also adds the required javascript call to the page output.
729 * @param core_renderer $output
730 * @return string HTML
732 protected function formatted_contents($output) {
733 // based of code in admin_tree
734 global $PAGE; // TODO change this when there is a proper way for blocks to get stuff into head.
735 static $eventattached;
736 if ($eventattached===null) {
737 $eventattached = true;
739 if (!$this->content) {
740 $this->content = new stdClass;
741 $this->content->items = array();
743 $this->get_required_javascript();
744 $this->get_content();
745 $content = $output->tree_block_contents($this->content->items,array('class'=>'block_tree list'));
746 if (isset($this->id) && !is_numeric($this->id)) {
747 $content = $output->box($content, 'block_tree_box', $this->id);
749 return $content;