MDL-44732 add cli script for execution of scheduled tasks
[moodle.git] / blocks / moodleblock.class.php
blob87f4707044cf76fe1fcd524146f83116796c9777
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 * A string generated by {@link _add_edit_controls()} to display block manipulation links when the user is in editing mode.
80 * @var string $edit_controls
82 var $edit_controls = NULL;
84 /**
85 * The initialized instance of this block object.
86 * @var block $instance
88 var $instance = NULL;
90 /**
91 * The page that this block is appearing on.
92 * @var moodle_page
94 public $page = NULL;
96 /**
97 * This blocks's context.
98 * @var stdClass
100 public $context = NULL;
103 * An object containing the instance configuration information for the current instance of this block.
104 * @var stdObject $config
106 var $config = NULL;
109 * How often the cronjob should run, 0 if not at all.
110 * @var int $cron
113 var $cron = NULL;
115 /// Class Functions
118 * Fake constructor to keep PHP5 happy
121 function __construct() {
122 $this->init();
126 * Function that can be overridden to do extra cleanup before
127 * the database tables are deleted. (Called once per block, not per instance!)
129 function before_delete() {
133 * Returns the block name, as present in the class name,
134 * the database, the block directory, etc etc.
136 * @return string
138 function name() {
139 // Returns the block name, as present in the class name,
140 // the database, the block directory, etc etc.
141 static $myname;
142 if ($myname === NULL) {
143 $myname = strtolower(get_class($this));
144 $myname = substr($myname, strpos($myname, '_') + 1);
146 return $myname;
150 * Parent class version of this function simply returns NULL
151 * This should be implemented by the derived class to return
152 * the content object.
154 * @return stdObject
156 function get_content() {
157 // This should be implemented by the derived class.
158 return NULL;
162 * Returns the class $title var value.
164 * Intentionally doesn't check if a title is set.
165 * This is already done in {@link _self_test()}
167 * @return string $this->title
169 function get_title() {
170 // Intentionally doesn't check if a title is set. This is already done in _self_test()
171 return $this->title;
175 * Returns the class $content_type var value.
177 * Intentionally doesn't check if content_type is set.
178 * This is already done in {@link _self_test()}
180 * @return string $this->content_type
182 function get_content_type() {
183 // Intentionally doesn't check if a content_type is set. This is already done in _self_test()
184 return $this->content_type;
188 * Returns true or false, depending on whether this block has any content to display
189 * and whether the user has permission to view the block
191 * @return boolean
193 function is_empty() {
194 if ( !has_capability('moodle/block:view', $this->context) ) {
195 return true;
198 $this->get_content();
199 return(empty($this->content->text) && empty($this->content->footer));
203 * First sets the current value of $this->content to NULL
204 * then calls the block's {@link get_content()} function
205 * to set its value back.
207 * @return stdObject
209 function refresh_content() {
210 // Nothing special here, depends on content()
211 $this->content = NULL;
212 return $this->get_content();
216 * Return a block_contents object representing the full contents of this block.
218 * This internally calls ->get_content(), and then adds the editing controls etc.
220 * You probably should not override this method, but instead override
221 * {@link html_attributes()}, {@link formatted_contents()} or {@link get_content()},
222 * {@link hide_header()}, {@link (get_edit_controls)}, etc.
224 * @return block_contents a representation of the block, for rendering.
225 * @since Moodle 2.0.
227 public function get_content_for_output($output) {
228 global $CFG;
230 $bc = new block_contents($this->html_attributes());
231 $bc->attributes['data-block'] = $this->name();
232 $bc->blockinstanceid = $this->instance->id;
233 $bc->blockpositionid = $this->instance->blockpositionid;
235 if ($this->instance->visible) {
236 $bc->content = $this->formatted_contents($output);
237 if (!empty($this->content->footer)) {
238 $bc->footer = $this->content->footer;
240 } else {
241 $bc->add_class('invisible');
244 if (!$this->hide_header()) {
245 $bc->title = $this->title;
248 if (empty($bc->title)) {
249 $bc->arialabel = new lang_string('pluginname', get_class($this));
250 $this->arialabel = $bc->arialabel;
253 if ($this->page->user_is_editing()) {
254 $bc->controls = $this->page->blocks->edit_controls($this);
255 } else {
256 // we must not use is_empty on hidden blocks
257 if ($this->is_empty() && !$bc->controls) {
258 return null;
262 if (empty($CFG->allowuserblockhiding)
263 || (empty($bc->content) && empty($bc->footer))
264 || !$this->instance_can_be_collapsed()) {
265 $bc->collapsible = block_contents::NOT_HIDEABLE;
266 } else if (get_user_preferences('block' . $bc->blockinstanceid . 'hidden', false)) {
267 $bc->collapsible = block_contents::HIDDEN;
268 } else {
269 $bc->collapsible = block_contents::VISIBLE;
272 if ($this->instance_can_be_docked() && !$this->hide_header()) {
273 $bc->dockable = true;
276 $bc->annotation = ''; // TODO MDL-19398 need to work out what to say here.
278 return $bc;
282 * Convert the contents of the block to HTML.
284 * This is used by block base classes like block_list to convert the structured
285 * $this->content->list and $this->content->icons arrays to HTML. So, in most
286 * blocks, you probaby want to override the {@link get_contents()} method,
287 * which generates that structured representation of the contents.
289 * @param $output The core_renderer to use when generating the output.
290 * @return string the HTML that should appearn in the body of the block.
291 * @since Moodle 2.0.
293 protected function formatted_contents($output) {
294 $this->get_content();
295 $this->get_required_javascript();
296 if (!empty($this->content->text)) {
297 return $this->content->text;
298 } else {
299 return '';
304 * Tests if this block has been implemented correctly.
305 * Also, $errors isn't used right now
307 * @return boolean
310 function _self_test() {
311 // Tests if this block has been implemented correctly.
312 // Also, $errors isn't used right now
313 $errors = array();
315 $correct = true;
316 if ($this->get_title() === NULL) {
317 $errors[] = 'title_not_set';
318 $correct = false;
320 if (!in_array($this->get_content_type(), array(BLOCK_TYPE_LIST, BLOCK_TYPE_TEXT, BLOCK_TYPE_TREE))) {
321 $errors[] = 'invalid_content_type';
322 $correct = false;
324 //following selftest was not working when roles&capabilities were used from block
325 /* if ($this->get_content() === NULL) {
326 $errors[] = 'content_not_set';
327 $correct = false;
329 $formats = $this->applicable_formats();
330 if (empty($formats) || array_sum($formats) === 0) {
331 $errors[] = 'no_formats';
332 $correct = false;
335 $width = $this->preferred_width();
336 if (!is_int($width) || $width <= 0) {
337 $errors[] = 'invalid_width';
338 $correct = false;
340 return $correct;
344 * Subclasses should override this and return true if the
345 * subclass block has a settings.php file.
347 * @return boolean
349 function has_config() {
350 return false;
354 * Default behavior: save all variables as $CFG properties
355 * You don't need to override this if you 're satisfied with the above
357 * @param array $data
358 * @return boolean
360 function config_save($data) {
361 foreach ($data as $name => $value) {
362 set_config($name, $value);
364 return true;
368 * Which page types this block may appear on.
370 * The information returned here is processed by the
371 * {@link blocks_name_allowed_in_format()} function. Look there if you need
372 * to know exactly how this works.
374 * Default case: everything except mod and tag.
376 * @return array page-type prefix => true/false.
378 function applicable_formats() {
379 // Default case: the block can be used in courses and site index, but not in activities
380 return array('all' => true, 'mod' => false, 'tag' => false);
385 * Default return is false - header will be shown
386 * @return boolean
388 function hide_header() {
389 return false;
393 * Return any HTML attributes that you want added to the outer <div> that
394 * of the block when it is output.
396 * Because of the way certain JS events are wired it is a good idea to ensure
397 * that the default values here still get set.
398 * I found the easiest way to do this and still set anything you want is to
399 * override it within your block in the following way
401 * <code php>
402 * function html_attributes() {
403 * $attributes = parent::html_attributes();
404 * $attributes['class'] .= ' mynewclass';
405 * return $attributes;
407 * </code>
409 * @return array attribute name => value.
411 function html_attributes() {
412 $attributes = array(
413 'id' => 'inst' . $this->instance->id,
414 'class' => 'block_' . $this->name(). ' block',
415 'role' => $this->get_aria_role()
417 if ($this->hide_header()) {
418 $attributes['class'] .= ' no-header';
420 if ($this->instance_can_be_docked() && get_user_preferences('docked_block_instance_'.$this->instance->id, 0)) {
421 $attributes['class'] .= ' dock_on_load';
423 return $attributes;
427 * Set up a particular instance of this class given data from the block_insances
428 * table and the current page. (See {@link block_manager::load_blocks()}.)
430 * @param stdClass $instance data from block_insances, block_positions, etc.
431 * @param moodle_page $the page this block is on.
433 function _load_instance($instance, $page) {
434 if (!empty($instance->configdata)) {
435 $this->config = unserialize(base64_decode($instance->configdata));
437 $this->instance = $instance;
438 $this->context = context_block::instance($instance->id);
439 $this->page = $page;
440 $this->specialization();
444 * Allows the block to load any JS it requires into the page.
446 * By default this function simply permits the user to dock the block if it is dockable.
448 function get_required_javascript() {
449 if ($this->instance_can_be_docked() && !$this->hide_header()) {
450 user_preference_allow_ajax_update('docked_block_instance_'.$this->instance->id, PARAM_INT);
455 * This function is called on your subclass right after an instance is loaded
456 * Use this function to act on instance data just after it's loaded and before anything else is done
457 * For instance: if your block will have different title's depending on location (site, course, blog, etc)
459 function specialization() {
460 // Just to make sure that this method exists.
464 * Is each block of this type going to have instance-specific configuration?
465 * Normally, this setting is controlled by {@link instance_allow_multiple()}: if multiple
466 * instances are allowed, then each will surely need its own configuration. However, in some
467 * cases it may be necessary to provide instance configuration to blocks that do not want to
468 * allow multiple instances. In that case, make this function return true.
469 * I stress again that this makes a difference ONLY if {@link instance_allow_multiple()} returns false.
470 * @return boolean
472 function instance_allow_config() {
473 return false;
477 * Are you going to allow multiple instances of each block?
478 * If yes, then it is assumed that the block WILL USE per-instance configuration
479 * @return boolean
481 function instance_allow_multiple() {
482 // Are you going to allow multiple instances of each block?
483 // If yes, then it is assumed that the block WILL USE per-instance configuration
484 return false;
488 * Default behavior: print the config_instance.html file
489 * You don't need to override this if you're satisfied with the above
491 * @deprecated since Moodle 2.0.
492 * @return boolean whether anything was done. Blocks should use edit_form.php.
494 function instance_config_print() {
495 global $CFG, $DB, $OUTPUT;
496 // Default behavior: print the config_instance.html file
497 // You don't need to override this if you're satisfied with the above
498 if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
499 return false;
502 if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
503 echo $OUTPUT->box_start('generalbox boxaligncenter blockconfiginstance');
504 include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
505 echo $OUTPUT->box_end();
506 } else {
507 notice(get_string('blockconfigbad'), str_replace('blockaction=', 'dummy=', qualified_me()));
510 return true;
514 * Serialize and store config data
516 function instance_config_save($data, $nolongerused = false) {
517 global $DB;
518 $DB->set_field('block_instances', 'configdata', base64_encode(serialize($data)),
519 array('id' => $this->instance->id));
523 * Replace the instance's configuration data with those currently in $this->config;
525 function instance_config_commit($nolongerused = false) {
526 global $DB;
527 $this->instance_config_save($this->config);
531 * Do any additional initialization you may need at the time a new block instance is created
532 * @return boolean
534 function instance_create() {
535 return true;
539 * Delete everything related to this instance if you have been using persistent storage other than the configdata field.
540 * @return boolean
542 function instance_delete() {
543 return true;
547 * Allows the block class to have a say in the user's ability to edit (i.e., configure) blocks of this type.
548 * The framework has first say in whether this will be allowed (e.g., no editing allowed unless in edit mode)
549 * but if the framework does allow it, the block can still decide to refuse.
550 * @return boolean
552 function user_can_edit() {
553 global $USER;
555 if (has_capability('moodle/block:edit', $this->context)) {
556 return true;
559 // The blocks in My Moodle are a special case. We want them to inherit from the user context.
560 if (!empty($USER->id)
561 && $this->instance->parentcontextid == $this->page->context->id // Block belongs to this page
562 && $this->page->context->contextlevel == CONTEXT_USER // Page belongs to a user
563 && $this->page->context->instanceid == $USER->id) { // Page belongs to this user
564 return has_capability('moodle/my:manageblocks', $this->page->context);
567 return false;
571 * Allows the block class to have a say in the user's ability to create new instances of this block.
572 * The framework has first say in whether this will be allowed (e.g., no adding allowed unless in edit mode)
573 * but if the framework does allow it, the block can still decide to refuse.
574 * This function has access to the complete page object, the creation related to which is being determined.
576 * @param moodle_page $page
577 * @return boolean
579 function user_can_addto($page) {
580 global $USER;
582 // The blocks in My Moodle are a special case and use a different capability.
583 if (!empty($USER->id)
584 && $page->context->contextlevel == CONTEXT_USER // Page belongs to a user
585 && $page->context->instanceid == $USER->id // Page belongs to this user
586 && $page->pagetype == 'my-index') { // Ensure we are on the My Moodle page
587 $capability = 'block/' . $this->name() . ':myaddinstance';
588 return $this->has_add_block_capability($page, $capability)
589 && has_capability('moodle/my:manageblocks', $page->context);
592 $capability = 'block/' . $this->name() . ':addinstance';
593 if ($this->has_add_block_capability($page, $capability)
594 && has_capability('moodle/block:edit', $page->context)) {
595 return true;
598 return false;
602 * Returns true if the user can add a block to a page.
604 * @param moodle_page $page
605 * @param string $capability the capability to check
606 * @return boolean true if user can add a block, false otherwise.
608 private function has_add_block_capability($page, $capability) {
609 // Check if the capability exists.
610 if (!get_capability_info($capability)) {
611 // Debug warning that the capability does not exist, but no more than once per page.
612 static $warned = array();
613 if (!isset($warned[$this->name()])) {
614 debugging('The block ' .$this->name() . ' does not define the standard capability ' .
615 $capability , DEBUG_DEVELOPER);
616 $warned[$this->name()] = 1;
618 // If the capability does not exist, the block can always be added.
619 return true;
620 } else {
621 return has_capability($capability, $page->context);
625 static function get_extra_capabilities() {
626 return array('moodle/block:view', 'moodle/block:edit');
629 // Methods deprecated in Moodle 2.0 ========================================
632 * Default case: the block wants to be 180 pixels wide
633 * @deprecated since Moodle 2.0.
634 * @return int
636 function preferred_width() {
637 return 180;
640 /** @deprecated since Moodle 2.0. */
641 function _print_block() {
642 throw new coding_exception('_print_block is no longer used. It was a private ' .
643 'method of the block class, only for use by the blocks system. You ' .
644 'should not have been calling it anyway.');
647 /** @deprecated since Moodle 2.0. */
648 function _print_shadow() {
649 throw new coding_exception('_print_shadow is no longer used. It was a private ' .
650 'method of the block class, only for use by the blocks system. You ' .
651 'should not have been calling it anyway.');
654 /** @deprecated since Moodle 2.0. */
655 function _title_html() {
656 throw new coding_exception('_title_html is no longer used. It was a private ' .
657 'method of the block class, only for use by the blocks system. You ' .
658 'should not have been calling it anyway.');
661 /** @deprecated since Moodle 2.0. */
662 function _add_edit_controls() {
663 throw new coding_exception('_add_edit_controls is no longer used. It was a private ' .
664 'method of the block class, only for use by the blocks system. You ' .
665 'should not have been calling it anyway.');
668 /** @deprecated since Moodle 2.0. */
669 function config_print() {
670 throw new coding_exception('config_print() can no longer be used. Blocks should use a settings.php file.');
674 * Can be overridden by the block to prevent the block from being dockable.
676 * @return bool
678 public function instance_can_be_docked() {
679 global $CFG;
680 return (!empty($CFG->allowblockstodock) && $this->page->theme->enable_dock);
684 * If overridden and set to false by the block it will not be hidable when
685 * editing is turned on.
687 * @return bool
689 public function instance_can_be_hidden() {
690 return true;
694 * If overridden and set to false by the block it will not be collapsible.
696 * @return bool
698 public function instance_can_be_collapsed() {
699 return true;
702 /** @callback callback functions for comments api */
703 public static function comment_template($options) {
704 $ret = <<<EOD
705 <div class="comment-userpicture">___picture___</div>
706 <div class="comment-content">
707 ___name___ - <span>___time___</span>
708 <div>___content___</div>
709 </div>
710 EOD;
711 return $ret;
713 public static function comment_permissions($options) {
714 return array('view'=>true, 'post'=>true);
716 public static function comment_url($options) {
717 return null;
719 public static function comment_display($comments, $options) {
720 return $comments;
722 public static function comment_add(&$comments, $options) {
723 return true;
727 * Returns the aria role attribute that best describes this block.
729 * Region is the default, but this should be overridden by a block is there is a region child, or even better
730 * a landmark child.
732 * Options are as follows:
733 * - landmark
734 * - application
735 * - banner
736 * - complementary
737 * - contentinfo
738 * - form
739 * - main
740 * - navigation
741 * - search
743 * @return string
745 public function get_aria_role() {
746 return 'complementary';
751 * Specialized class for displaying a block with a list of icons/text labels
753 * The get_content method should set $this->content->items and (optionally)
754 * $this->content->icons, instead of $this->content->text.
756 * @author Jon Papaioannou
757 * @package core_block
760 class block_list extends block_base {
761 var $content_type = BLOCK_TYPE_LIST;
763 function is_empty() {
764 if ( !has_capability('moodle/block:view', $this->context) ) {
765 return true;
768 $this->get_content();
769 return (empty($this->content->items) && empty($this->content->footer));
772 protected function formatted_contents($output) {
773 $this->get_content();
774 $this->get_required_javascript();
775 if (!empty($this->content->items)) {
776 return $output->list_block_contents($this->content->icons, $this->content->items);
777 } else {
778 return '';
782 function html_attributes() {
783 $attributes = parent::html_attributes();
784 $attributes['class'] .= ' list_block';
785 return $attributes;
791 * Specialized class for displaying a tree menu.
793 * The {@link get_content()} method involves setting the content of
794 * <code>$this->content->items</code> with an array of {@link tree_item}
795 * objects (these are the top-level nodes). The {@link tree_item::children}
796 * property may contain more tree_item objects, and so on. The tree_item class
797 * itself is abstract and not intended for use, use one of it's subclasses.
799 * Unlike {@link block_list}, the icons are specified as part of the items,
800 * not in a separate array.
802 * @author Alan Trick
803 * @package core_block
804 * @internal this extends block_list so we get is_empty() for free
806 class block_tree extends block_list {
809 * @var int specifies the manner in which contents should be added to this
810 * block type. In this case <code>$this->content->items</code> is used with
811 * {@link tree_item}s.
813 public $content_type = BLOCK_TYPE_TREE;
816 * Make the formatted HTML ouput.
818 * Also adds the required javascript call to the page output.
820 * @param core_renderer $output
821 * @return string HTML
823 protected function formatted_contents($output) {
824 // based of code in admin_tree
825 global $PAGE; // TODO change this when there is a proper way for blocks to get stuff into head.
826 static $eventattached;
827 if ($eventattached===null) {
828 $eventattached = true;
830 if (!$this->content) {
831 $this->content = new stdClass;
832 $this->content->items = array();
834 $this->get_required_javascript();
835 $this->get_content();
836 $content = $output->tree_block_contents($this->content->items,array('class'=>'block_tree list'));
837 if (isset($this->id) && !is_numeric($this->id)) {
838 $content = $output->box($content, 'block_tree_box', $this->id);
840 return $content;