Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  
   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.
  14  //
  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/>.
  17  
  18  /**
  19   * This file contains the renderers for the calendar within Moodle
  20   *
  21   * @copyright 2010 Sam Hemelryk
  22   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   * @package calendar
  24   */
  25  
  26  if (!defined('MOODLE_INTERNAL')) {
  27      die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
  28  }
  29  
  30  /**
  31   * The primary renderer for the calendar.
  32   */
  33  class core_calendar_renderer extends plugin_renderer_base {
  34  
  35      /**
  36       * Starts the standard layout for the page
  37       *
  38       * @return string
  39       */
  40      public function start_layout() {
  41          return html_writer::start_tag('div', ['data-region' => 'calendar', 'class' => 'maincalendar']);
  42      }
  43  
  44      /**
  45       * Creates the remainder of the layout
  46       *
  47       * @return string
  48       */
  49      public function complete_layout() {
  50          return html_writer::end_tag('div');
  51      }
  52  
  53      /**
  54       * Produces the content for the three months block (pretend block)
  55       *
  56       * This includes the previous month, the current month, and the next month
  57       *
  58       * @deprecated since 4.0 MDL-72810.
  59       * @todo MDL-73117 This will be deleted in Moodle 4.4.
  60       *
  61       * @param calendar_information $calendar
  62       * @return string
  63       */
  64      public function fake_block_threemonths(calendar_information $calendar) {
  65          debugging('This method is no longer used as the three month calendar block has been removed', DEBUG_DEVELOPER);
  66  
  67          // Get the calendar type we are using.
  68          $calendartype = \core_calendar\type_factory::get_calendar_instance();
  69          $time = $calendartype->timestamp_to_date_array($calendar->time);
  70  
  71          $current = $calendar->time;
  72          $prevmonthyear = $calendartype->get_prev_month($time['year'], $time['mon']);
  73          $prev = $calendartype->convert_to_timestamp(
  74                  $prevmonthyear[1],
  75                  $prevmonthyear[0],
  76                  1
  77              );
  78          $nextmonthyear = $calendartype->get_next_month($time['year'], $time['mon']);
  79          $next = $calendartype->convert_to_timestamp(
  80                  $nextmonthyear[1],
  81                  $nextmonthyear[0],
  82                  1
  83              );
  84  
  85          $content = '';
  86  
  87          // Previous.
  88          $calendar->set_time($prev);
  89          list($previousmonth, ) = calendar_get_view($calendar, 'minithree', false, true);
  90  
  91          // Current month.
  92          $calendar->set_time($current);
  93          list($currentmonth, ) = calendar_get_view($calendar, 'minithree', false, true);
  94  
  95          // Next month.
  96          $calendar->set_time($next);
  97          list($nextmonth, ) = calendar_get_view($calendar, 'minithree', false, true);
  98  
  99          // Reset the time back.
 100          $calendar->set_time($current);
 101  
 102          $data = (object) [
 103              'previousmonth' => $previousmonth,
 104              'currentmonth' => $currentmonth,
 105              'nextmonth' => $nextmonth,
 106          ];
 107  
 108          $template = 'core_calendar/calendar_threemonth';
 109          $content .= $this->render_from_template($template, $data);
 110          return $content;
 111      }
 112  
 113      /**
 114       * Adds a pretent calendar block
 115       *
 116       * @param block_contents $bc
 117       * @param mixed $pos BLOCK_POS_RIGHT | BLOCK_POS_LEFT
 118       */
 119      public function add_pretend_calendar_block(block_contents $bc, $pos=BLOCK_POS_RIGHT) {
 120          $this->page->blocks->add_fake_block($bc, $pos);
 121      }
 122  
 123      /**
 124       * Creates a button to add a new event.
 125       *
 126       * @param int $courseid
 127       * @param int $unused1
 128       * @param int $unused2
 129       * @param int $unused3
 130       * @param int $unused4
 131       * @return string
 132       */
 133      public function add_event_button($courseid, $unused1 = null, $unused2 = null, $unused3 = null, $unused4 = null) {
 134          $data = [
 135              'contextid' => (\context_course::instance($courseid))->id,
 136          ];
 137          return $this->render_from_template('core_calendar/add_event_button', $data);
 138      }
 139  
 140      /**
 141       * Displays an event
 142       *
 143       * @deprecated since 3.9
 144       *
 145       * @param calendar_event $event
 146       * @param bool $showactions
 147       * @return string
 148       */
 149      public function event(calendar_event $event, $showactions=true) {
 150          global $CFG;
 151          debugging('This function is no longer used', DEBUG_DEVELOPER);
 152  
 153          $event = calendar_add_event_metadata($event);
 154          $context = $event->context;
 155          $output = '';
 156  
 157          $output .= $this->output->box_start('card-header clearfix');
 158          if (calendar_edit_event_allowed($event) && $showactions) {
 159              if (calendar_delete_event_allowed($event)) {
 160                  $editlink = new moodle_url(CALENDAR_URL.'event.php', array('action' => 'edit', 'id' => $event->id));
 161                  $deletelink = new moodle_url(CALENDAR_URL.'delete.php', array('id' => $event->id));
 162                  if (!empty($event->calendarcourseid)) {
 163                      $editlink->param('course', $event->calendarcourseid);
 164                      $deletelink->param('course', $event->calendarcourseid);
 165                  }
 166              } else {
 167                  $params = array('update' => $event->cmid, 'return' => true, 'sesskey' => sesskey());
 168                  $editlink = new moodle_url('/course/mod.php', $params);
 169                  $deletelink = null;
 170              }
 171  
 172              $commands  = html_writer::start_tag('div', array('class' => 'commands float-sm-right'));
 173              $commands .= html_writer::start_tag('a', array('href' => $editlink));
 174              $str = get_string('tt_editevent', 'calendar');
 175              $commands .= $this->output->pix_icon('t/edit', $str);
 176              $commands .= html_writer::end_tag('a');
 177              if ($deletelink != null) {
 178                  $commands .= html_writer::start_tag('a', array('href' => $deletelink));
 179                  $str = get_string('tt_deleteevent', 'calendar');
 180                  $commands .= $this->output->pix_icon('t/delete', $str);
 181                  $commands .= html_writer::end_tag('a');
 182              }
 183              $commands .= html_writer::end_tag('div');
 184              $output .= $commands;
 185          }
 186          if (!empty($event->icon)) {
 187              $output .= $event->icon;
 188          } else {
 189              $output .= $this->output->spacer(array('height' => 16, 'width' => 16));
 190          }
 191  
 192          if (!empty($event->referer)) {
 193              $output .= $this->output->heading($event->referer, 3, array('class' => 'referer'));
 194          } else {
 195              $output .= $this->output->heading(
 196                  format_string($event->name, false, array('context' => $context)),
 197                  3,
 198                  array('class' => 'name d-inline-block')
 199              );
 200          }
 201          // Show subscription source if needed.
 202          if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
 203              if (!empty($event->subscription->url)) {
 204                  $source = html_writer::link($event->subscription->url,
 205                          get_string('subscriptionsource', 'calendar', $event->subscription->name));
 206              } else {
 207                  // File based ical.
 208                  $source = get_string('subscriptionsource', 'calendar', $event->subscription->name);
 209              }
 210              $output .= html_writer::tag('div', $source, array('class' => 'subscription'));
 211          }
 212          if (!empty($event->courselink)) {
 213              $output .= html_writer::tag('div', $event->courselink);
 214          }
 215          if (!empty($event->time)) {
 216              $output .= html_writer::tag('span', $event->time, array('class' => 'date float-sm-right mr-1'));
 217          } else {
 218              $attrs = array('class' => 'date float-sm-right mr-1');
 219              $output .= html_writer::tag('span', calendar_time_representation($event->timestart), $attrs);
 220          }
 221  
 222          if (!empty($event->actionurl)) {
 223              $actionlink = html_writer::link(new moodle_url($event->actionurl), $event->actionname);
 224              $output .= html_writer::tag('div', $actionlink, ['class' => 'action']);
 225          }
 226  
 227          $output .= $this->output->box_end();
 228          $eventdetailshtml = '';
 229          $eventdetailsclasses = '';
 230  
 231          $eventdetailshtml .= format_text($event->description, $event->format, array('context' => $context));
 232          $eventdetailsclasses .= 'description card-block';
 233          if (isset($event->cssclass)) {
 234              $eventdetailsclasses .= ' '.$event->cssclass;
 235          }
 236  
 237          if (!empty($eventdetailshtml)) {
 238              $output .= html_writer::tag('div', $eventdetailshtml, array('class' => $eventdetailsclasses));
 239          }
 240  
 241          $eventhtml = html_writer::tag('div', $output, array('class' => 'card'));
 242          return html_writer::tag('div', $eventhtml, array('class' => 'event', 'id' => 'event_' . $event->id));
 243      }
 244  
 245      /**
 246       * Displays a course filter selector
 247       *
 248       * @param moodle_url $returnurl The URL that the user should be taken too upon selecting a course.
 249       * @param string $label The label to use for the course select.
 250       * @param int $courseid The id of the course to be selected.
 251       * @param int|null $calendarinstanceid The instance ID of the calendar we're generating this course filter for.
 252       * @return string
 253       */
 254      public function course_filter_selector(moodle_url $returnurl, $label = null, $courseid = null, int $calendarinstanceid = null) {
 255          global $CFG, $DB;
 256  
 257          if (!isloggedin() or isguestuser()) {
 258              return '';
 259          }
 260  
 261          $contextrecords = [];
 262          $courses = calendar_get_default_courses($courseid, 'id, shortname');
 263  
 264          if (!empty($courses) && count($courses) > CONTEXT_CACHE_MAX_SIZE) {
 265              // We need to pull the context records from the DB to preload them
 266              // below. The calendar_get_default_courses code will actually preload
 267              // the contexts itself however the context cache is capped to a certain
 268              // amount before it starts recycling. Unfortunately that starts to happen
 269              // quite a bit if a user has access to a large number of courses (e.g. admin).
 270              // So in order to avoid hitting the DB for each context as we loop below we
 271              // can load all of the context records and add them to the cache just in time.
 272              $courseids = array_map(function($c) {
 273                  return $c->id;
 274              }, $courses);
 275              list($insql, $params) = $DB->get_in_or_equal($courseids);
 276              $contextsql = "SELECT ctx.instanceid, " . context_helper::get_preload_record_columns_sql('ctx') .
 277                            " FROM {context} ctx WHERE ctx.contextlevel = ? AND ctx.instanceid $insql";
 278              array_unshift($params, CONTEXT_COURSE);
 279              $contextrecords = $DB->get_records_sql($contextsql, $params);
 280          }
 281  
 282          unset($courses[SITEID]);
 283  
 284          $courseoptions = array();
 285          $courseoptions[SITEID] = get_string('fulllistofcourses');
 286          foreach ($courses as $course) {
 287              if (isset($contextrecords[$course->id])) {
 288                  context_helper::preload_from_record($contextrecords[$course->id]);
 289              }
 290              $coursecontext = context_course::instance($course->id);
 291              $courseoptions[$course->id] = format_string($course->shortname, true, array('context' => $coursecontext));
 292          }
 293  
 294          if ($courseid) {
 295              $selected = $courseid;
 296          } else if ($this->page->course->id !== SITEID) {
 297              $selected = $this->page->course->id;
 298          } else {
 299              $selected = '';
 300          }
 301          $courseurl = new moodle_url($returnurl);
 302          $courseurl->remove_params('course');
 303  
 304          $labelattributes = [];
 305          if (empty($label)) {
 306              $label = get_string('listofcourses');
 307              $labelattributes['class'] = 'sr-only';
 308          }
 309  
 310          $filterid = 'calendar-course-filter';
 311          if ($calendarinstanceid) {
 312              $filterid .= "-$calendarinstanceid";
 313          }
 314          $select = html_writer::label($label, $filterid, false, $labelattributes);
 315          $select .= html_writer::select($courseoptions, 'course', $selected, false,
 316                  ['class' => 'cal_courses_flt ml-1 mr-auto', 'id' => $filterid]);
 317  
 318          return $select;
 319      }
 320  
 321      /**
 322       * Render the subscriptions header
 323       *
 324       * @return string
 325       */
 326      public function render_subscriptions_header(): string {
 327          $importcalendarbutton = new single_button(new moodle_url('/calendar/import.php', calendar_get_export_import_link_params()),
 328                  get_string('importcalendar', 'calendar'), 'get', true);
 329          $importcalendarbutton->class .= ' float-sm-right float-right';
 330          $exportcalendarbutton = new single_button(new moodle_url('/calendar/export.php', calendar_get_export_import_link_params()),
 331                  get_string('exportcalendar', 'calendar'), 'get', true);
 332          $exportcalendarbutton->class .= ' float-sm-right float-right';
 333          $output = $this->output->heading(get_string('managesubscriptions', 'calendar'));
 334          $output .= html_writer::start_div('header d-flex flex-wrap mt-5');
 335          $headerattr = [
 336              'class' => 'mr-auto',
 337              'aria-describedby' => 'subscription_details_table',
 338          ];
 339          $output .= html_writer::tag('h3', get_string('yoursubscriptions', 'calendar'), $headerattr);
 340          $output .= $this->output->render($importcalendarbutton);
 341          $output .= $this->output->render($exportcalendarbutton);
 342          $output .= html_writer::end_div();
 343  
 344          return $output;
 345      }
 346  
 347      /**
 348       * Render the subscriptions blank state appearance
 349       *
 350       * @return string
 351       */
 352      public function render_no_calendar_subscriptions(): string {
 353          $output = html_writer::start_div('mt-5');
 354          $importlink = html_writer::link((new moodle_url('/calendar/import.php', calendar_get_export_import_link_params()))->out(),
 355                  get_string('importcalendarexternal', 'calendar'));
 356          $output .= get_string('nocalendarsubscriptions', 'calendar', $importlink);
 357          $output .= html_writer::end_div();
 358  
 359          return $output;
 360      }
 361  
 362      /**
 363       * Renders a table containing information about calendar subscriptions.
 364       *
 365       * @param int $unused
 366       * @param array $subscriptions
 367       * @param string $unused2
 368       * @return string
 369       */
 370      public function subscription_details($unused, $subscriptions, $unused2 = '') {
 371          $table = new html_table();
 372          $table->head  = array(
 373              get_string('colcalendar', 'calendar'),
 374              get_string('collastupdated', 'calendar'),
 375              get_string('eventkind', 'calendar'),
 376              get_string('colpoll', 'calendar'),
 377              get_string('colactions', 'calendar')
 378          );
 379          $table->data  = array();
 380          $table->id = 'subscription_details_table';
 381  
 382          if (empty($subscriptions)) {
 383              $cell = new html_table_cell(get_string('nocalendarsubscriptions', 'calendar'));
 384              $cell->colspan = 5;
 385              $table->data[] = new html_table_row(array($cell));
 386          }
 387          $strnever = new lang_string('never', 'calendar');
 388          foreach ($subscriptions as $sub) {
 389              $label = $sub->name;
 390              if (!empty($sub->url)) {
 391                  $label = html_writer::link($sub->url, $label);
 392              }
 393              if (empty($sub->lastupdated)) {
 394                  $lastupdated = $strnever->out();
 395              } else {
 396                  $lastupdated = userdate($sub->lastupdated, get_string('strftimedatetimeshort', 'langconfig'));
 397              }
 398  
 399              $type = $sub->eventtype . 'events';
 400              $calendarname = new html_table_cell($label);
 401              $calendarname->header = true;
 402  
 403              $tablerow = new html_table_row(array(
 404                  $calendarname,
 405                  new html_table_cell($lastupdated),
 406                  new html_table_cell(get_string($type, 'calendar')),
 407                  new html_table_cell($this->render_subscription_update_interval($sub)),
 408                  new html_table_cell($this->subscription_action_links())
 409              ));
 410              $tablerow->attributes += [
 411                  'data-subid' => $sub->id,
 412                  'data-subname' => $sub->name
 413              ];
 414              $table->data[] = $tablerow;
 415          }
 416  
 417          $out  = $this->output->box_start('generalbox calendarsubs');
 418  
 419          $out .= html_writer::table($table);
 420          $out .= $this->output->box_end();
 421  
 422          $this->page->requires->js_call_amd('core_calendar/manage_subscriptions', 'init');
 423          return $out;
 424      }
 425  
 426      /**
 427       * Render subscription update interval form.
 428       *
 429       * @param stdClass $subscription
 430       * @return string
 431       */
 432      protected function render_subscription_update_interval(stdClass $subscription): string {
 433          if (empty($subscription->url)) {
 434              return '';
 435          }
 436  
 437          $tmpl = new \core_calendar\output\refreshintervalcollection($subscription);
 438          return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output));
 439      }
 440  
 441      /**
 442       * Creates a form to perform actions on a given subscription.
 443       *
 444       * @return string
 445       */
 446      protected function subscription_action_links(): string {
 447          $html = html_writer::start_tag('div', array('class' => 'btn-group float-left'));
 448          $html .= html_writer::span(html_writer::link('#', get_string('delete'),
 449              ['data-action' => 'delete-subscription']), '');
 450          $html .= html_writer::end_tag('div');
 451          return $html;
 452      }
 453  
 454      /**
 455       * Render the event filter region.
 456       *
 457       * @return  string
 458       */
 459      public function event_filter() {
 460          $data = [
 461              'eventtypes' => calendar_get_filter_types(),
 462          ];
 463          return $this->render_from_template('core_calendar/event_filter', $data);
 464      }
 465  
 466      /**
 467       * Render the calendar import result.
 468       *
 469       * @param array $result Import result
 470       * @return string|null
 471       */
 472      public function render_import_result(array $result): ?string {
 473          $data = [
 474              'eventsimported' => $result['eventsimported'],
 475              'eventsskipped' => $result['eventsskipped'],
 476              'eventsupdated' => $result['eventsupdated'],
 477              'eventsdeleted' => $result['eventsdeleted'],
 478              'haserror' => $result['haserror'],
 479              'errors' => $result['errors']
 480          ];
 481  
 482          return $this->render_from_template('core_calendar/subscription_update_result', $data);
 483      }
 484  }