Search moodle.org's
Developer Documentation

  • Bug fixes for general core bugs in 3.11.x will end 9 May 2022 (12 months).
  • Bug fixes for security issues in 3.11.x will end 14 November 2022 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
  • Differences Between: [Versions 310 and 311] [Versions 35 and 311] [Versions 36 and 311] [Versions 37 and 311] [Versions 38 and 311] [Versions 39 and 311]

       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   * Renderer for use with the course section and all the goodness that falls
      20   * within it.
      21   *
      22   * This renderer should contain methods useful to courses, and categories.
      23   *
      24   * @package   moodlecore
      25   * @copyright 2010 Sam Hemelryk
      26   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      27   */
      28  
      29  /**
      30   * The core course renderer
      31   *
      32   * Can be retrieved with the following:
      33   * $renderer = $PAGE->get_renderer('core','course');
      34   */
      35  class core_course_renderer extends plugin_renderer_base {
      36      const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
      37      const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
      38      const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
      39      const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
      40      const COURSECAT_SHOW_COURSES_EXPANDED = 20;
      41      const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
      42  
      43      const COURSECAT_TYPE_CATEGORY = 0;
      44      const COURSECAT_TYPE_COURSE = 1;
      45  
      46      /**
      47       * A cache of strings
      48       * @var stdClass
      49       */
      50      protected $strings;
      51  
      52      /**
      53       * Whether a category content is being initially rendered with children. This is mainly used by the
      54       * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
      55       * page load.
      56       * @var bool
      57       */
      58      protected $categoryexpandedonload = false;
      59  
      60      /**
      61       * Override the constructor so that we can initialise the string cache
      62       *
      63       * @param moodle_page $page
      64       * @param string $target
      65       */
      66      public function __construct(moodle_page $page, $target) {
      67          $this->strings = new stdClass;
      68          parent::__construct($page, $target);
      69      }
      70  
      71      /**
      72       * @deprecated since 3.2
      73       */
      74      protected function add_modchoosertoggle() {
      75          throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
      76      }
      77  
      78      /**
      79       * Renders course info box.
      80       *
      81       * @param stdClass $course
      82       * @return string
      83       */
      84      public function course_info_box(stdClass $course) {
      85          $content = '';
      86          $content .= $this->output->box_start('generalbox info');
      87          $chelper = new coursecat_helper();
      88          $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
      89          $content .= $this->coursecat_coursebox($chelper, $course);
      90          $content .= $this->output->box_end();
      91          return $content;
      92      }
      93  
      94      /**
      95       * Renderers a structured array of courses and categories into a nice XHTML tree structure.
      96       *
      97       * @deprecated since 2.5
      98       *
      99       * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
     100       *
     101       * @param array $ignored argument ignored
     102       * @return string
     103       */
     104      public final function course_category_tree(array $ignored) {
     105          debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
     106          return $this->frontpage_combo_list();
     107      }
     108  
     109      /**
     110       * Renderers a category for use with course_category_tree
     111       *
     112       * @deprecated since 2.5
     113       *
     114       * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
     115       *
     116       * @param array $category
     117       * @param int $depth
     118       * @return string
     119       */
     120      protected final function course_category_tree_category(stdClass $category, $depth=1) {
     121          debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
     122          return '';
     123      }
     124  
     125      /**
     126       * Render a modchooser.
     127       *
     128       * @param renderable $modchooser The chooser.
     129       * @return string
     130       */
     131      public function render_modchooser(renderable $modchooser) {
     132          return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
     133      }
     134  
     135      /**
     136       * Build the HTML for the module chooser javascript popup
     137       *
     138       * @param array $modules A set of modules as returned form @see
     139       * get_module_metadata
     140       * @param object $course The course that will be displayed
     141       * @return string The composed HTML for the module
     142       */
     143      public function course_modchooser($modules, $course) {
     144          debugging('course_modchooser() is deprecated. Please use course_activitychooser() instead.', DEBUG_DEVELOPER);
     145  
     146          return $this->course_activitychooser($course->id);
     147      }
     148  
     149      /**
     150       * Build the HTML for the module chooser javascript popup.
     151       *
     152       * @param int $courseid The course id to fetch modules for.
     153       * @return string
     154       */
     155      public function course_activitychooser($courseid) {
     156  
     157          if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
     158              return '';
     159          }
     160  
     161          // Build an object of config settings that we can then hook into in the Activity Chooser.
     162          $chooserconfig = (object) [
     163              'tabmode' => get_config('core', 'activitychoosertabmode'),
     164          ];
     165          $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid, $chooserconfig]);
     166  
     167          return '';
     168      }
     169  
     170      /**
     171       * Build the HTML for a specified set of modules
     172       *
     173       * @param array $modules A set of modules as used by the
     174       * course_modchooser_module function
     175       * @return string The composed HTML for the module
     176       */
     177      protected function course_modchooser_module_types($modules) {
     178          debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
     179              'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
     180          return '';
     181      }
     182  
     183      /**
     184       * Return the HTML for the specified module adding any required classes
     185       *
     186       * @param object $module An object containing the title, and link. An
     187       * icon, and help text may optionally be specified. If the module
     188       * contains subtypes in the types option, then these will also be
     189       * displayed.
     190       * @param array $classes Additional classes to add to the encompassing
     191       * div element
     192       * @return string The composed HTML for the module
     193       */
     194      protected function course_modchooser_module($module, $classes = array('option')) {
     195          debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
     196              'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
     197          return '';
     198      }
     199  
     200      protected function course_modchooser_title($title, $identifier = null) {
     201          debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
     202              'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
     203          return '';
     204      }
     205  
     206      /**
     207       * Renders HTML for displaying the sequence of course module editing buttons
     208       *
     209       * @see course_get_cm_edit_actions()
     210       *
     211       * @param action_link[] $actions Array of action_link objects
     212       * @param cm_info $mod The module we are displaying actions for.
     213       * @param array $displayoptions additional display options:
     214       *     ownerselector => A JS/CSS selector that can be used to find an cm node.
     215       *         If specified the owning node will be given the class 'action-menu-shown' when the action
     216       *         menu is being displayed.
     217       *     constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
     218       *         the action menu to when it is being displayed.
     219       *     donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
     220       * @return string
     221       */
     222      public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
     223          global $CFG;
     224  
     225          if (empty($actions)) {
     226              return '';
     227          }
     228  
     229          if (isset($displayoptions['ownerselector'])) {
     230              $ownerselector = $displayoptions['ownerselector'];
     231          } else if ($mod) {
     232              $ownerselector = '#module-'.$mod->id;
     233          } else {
     234              debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
     235              $ownerselector = 'li.activity';
     236          }
     237  
     238          if (isset($displayoptions['constraintselector'])) {
     239              $constraint = $displayoptions['constraintselector'];
     240          } else {
     241              $constraint = '.course-content';
     242          }
     243  
     244          $menu = new action_menu();
     245          $menu->set_owner_selector($ownerselector);
     246          $menu->set_constraint($constraint);
     247          $menu->set_alignment(action_menu::TR, action_menu::BR);
     248          $menu->set_menu_trigger(get_string('edit'));
     249  
     250          foreach ($actions as $action) {
     251              if ($action instanceof action_menu_link) {
     252                  $action->add_class('cm-edit-action');
     253              }
     254              $menu->add($action);
     255          }
     256          $menu->attributes['class'] .= ' section-cm-edit-actions commands';
     257  
     258          // Prioritise the menu ahead of all other actions.
     259          $menu->prioritise = true;
     260  
     261          return $this->render($menu);
     262      }
     263  
     264      /**
     265       * Renders HTML for the menus to add activities and resources to the current course
     266       *
     267       * @param stdClass $course
     268       * @param int $section relative section number (field course_sections.section)
     269       * @param int $sectionreturn The section to link back to
     270       * @param array $displayoptions additional display options, for example blocks add
     271       *     option 'inblock' => true, suggesting to display controls vertically
     272       * @return string
     273       */
     274      function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
     275          // The returned control HTML can be one of the following:
     276          // - Only the non-ajax control (select menus of activities and resources) with a noscript fallback for non js clients.
     277          // Please note that non-ajax control has been deprecated and it will be removed in the future.
     278  
     279          // - Only the ajax control (the link which when clicked produces the activity chooser modal). No noscript fallback.
     280  
     281          $courseajaxenabled = course_ajax_enabled($course);
     282  
     283          // Non ajax control is under deprecated, $rendernonajaxcontrol will be removed in later versions.
     284          $rendernonajaxcontrol = !$courseajaxenabled || $course->id != $this->page->course->id;
     285          if ($rendernonajaxcontrol) {
     286              // The non-ajax control, which includes an entirely non-js (<noscript>) fallback too.
     287              return $this->course_section_add_cm_control_nonajax($course, $section, $sectionreturn, $displayoptions);
     288          } else {
     289              // The ajax control - the 'Add an activity or resource' link.
     290              // The module chooser link.
     291              $straddeither = get_string('addresourceoractivity');
     292              $ajaxcontrol = html_writer::start_tag('div', array('class' => 'mdl-right'));
     293              $ajaxcontrol .= html_writer::start_tag('div', array('class' => 'section-modchooser'));
     294              $icon = $this->output->pix_icon('t/add', '');
     295              $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
     296              $ajaxcontrol .= html_writer::tag('button', $icon . $span, [
     297                      'class' => 'section-modchooser-link btn btn-link',
     298                      'data-action' => 'open-chooser',
     299                      'data-sectionid' => $section,
     300                      'data-sectionreturnid' => $sectionreturn,
     301                  ]
     302              );
     303              $ajaxcontrol .= html_writer::end_tag('div');
     304              $ajaxcontrol .= html_writer::end_tag('div');
     305  
     306              // Load the JS for the modal.
     307              $this->course_activitychooser($course->id);
     308              return $ajaxcontrol;
     309          }
     310      }
     311  
     312      /**
     313       * Render the deprecated nonajax activity chooser.
     314       *
     315       * @deprecated since Moodle 3.11
     316       *
     317       * @todo MDL-71331 deprecate this function
     318       * @param stdClass $course the course object
     319       * @param int $section relative section number (field course_sections.section)
     320       * @param int $sectionreturn The section to link back to
     321       * @param array $displayoptions additional display options, for example blocks add
     322       *     option 'inblock' => true, suggesting to display controls vertically
     323       * @return string
     324       */
     325      private function course_section_add_cm_control_nonajax($course, $section, $sectionreturn = null,
     326              $displayoptions = array()): string {
     327          global $USER;
     328  
     329          $vertical = !empty($displayoptions['inblock']);
     330  
     331          // Check to see if user can add menus.
     332          if (
     333              !has_capability('moodle/course:manageactivities', context_course::instance($course->id))
     334              || !$this->page->user_is_editing()
     335          ) {
     336              return '';
     337          }
     338  
     339          debugging('non-js dropdowns are deprecated.', DEBUG_DEVELOPER);
     340          // Retrieve all modules with associated metadata.
     341          $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
     342          $urlparams = ['section' => $section];
     343          if (!is_null($sectionreturn)) {
     344              $urlparams['sr'] = $sectionreturn;
     345          }
     346          $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
     347  
     348          // Return if there are no content items to add.
     349          if (empty($modules)) {
     350              return '';
     351          }
     352  
     353          // We'll sort resources and activities into two lists.
     354          $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
     355  
     356          foreach ($modules as $module) {
     357              $activityclass = MOD_CLASS_ACTIVITY;
     358              if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
     359                  $activityclass = MOD_CLASS_RESOURCE;
     360              } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
     361                  // System modules cannot be added by user, do not add to dropdown.
     362                  continue;
     363              }
     364              $link = $module->link;
     365              $activities[$activityclass][$link] = $module->title;
     366          }
     367  
     368          $straddactivity = get_string('addactivity');
     369          $straddresource = get_string('addresource');
     370          $sectionname = get_section_name($course, $section);
     371          $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
     372          $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
     373  
     374          $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
     375              . $section));
     376  
     377          if (!$vertical) {
     378              $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
     379          }
     380  
     381          if (!empty($activities[MOD_CLASS_RESOURCE])) {
     382              $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
     383              $select->set_help_icon('resources');
     384              $select->set_label($strresourcelabel, array('class' => 'accesshide'));
     385              $nonajaxcontrol .= $this->output->render($select);
     386          }
     387  
     388          if (!empty($activities[MOD_CLASS_ACTIVITY])) {
     389              $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
     390              $select->set_help_icon('activities');
     391              $select->set_label($stractivitylabel, array('class' => 'accesshide'));
     392              $nonajaxcontrol .= $this->output->render($select);
     393          }
     394  
     395          if (!$vertical) {
     396              $nonajaxcontrol .= html_writer::end_tag('div');
     397          }
     398  
     399          $nonajaxcontrol .= html_writer::end_tag('div');
     400  
     401          return $nonajaxcontrol;
     402      }
     403  
     404      /**
     405       * Renders html to display a course search form
     406       *
     407       * @param string $value default value to populate the search field
     408       * @return string
     409       */
     410      public function course_search_form($value = '') {
     411  
     412          $data = [
     413              'action' => \core_search\manager::get_course_search_url(),
     414              'btnclass' => 'btn-primary',
     415              'inputname' => 'q',
     416              'searchstring' => get_string('searchcourses'),
     417              'hiddenfields' => (object) ['name' => 'areaids', 'value' => 'core_course-course'],
     418              'query' => $value
     419          ];
     420          return $this->render_from_template('core/search_input', $data);
     421      }
     422  
     423      /**
     424       * Renders html for completion box on course page
     425       *
     426       * If completion is disabled, returns empty string
     427       * If completion is automatic, returns an icon of the current completion state
     428       * If completion is manual, returns a form (with an icon inside) that allows user to
     429       * toggle completion
     430       *
     431       * @deprecated since Moodle 3.11
     432       * @todo MDL-71183 Final deprecation in Moodle 4.3.
     433       * @see \core_renderer::activity_information
     434       *
     435       * @param stdClass $course course object
     436       * @param completion_info $completioninfo completion info for the course, it is recommended
     437       *     to fetch once for all modules in course/section for performance
     438       * @param cm_info $mod module to show completion for
     439       * @param array $displayoptions display options, not used in core
     440       * @return string
     441       */
     442      public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
     443          global $CFG, $DB, $USER;
     444  
     445          debugging(__FUNCTION__ . ' is deprecated and is being replaced by the activity_information output component.',
     446              DEBUG_DEVELOPER);
     447  
     448          $output = '';
     449  
     450          $istrackeduser = $completioninfo->is_tracked_user($USER->id);
     451          $isediting = $this->page->user_is_editing();
     452  
     453          if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
     454              return $output;
     455          }
     456          if ($completioninfo === null) {
     457              $completioninfo = new completion_info($course);
     458          }
     459          $completion = $completioninfo->is_enabled($mod);
     460  
     461          if ($completion == COMPLETION_TRACKING_NONE) {
     462              if ($isediting) {
     463                  $output .= html_writer::span('&nbsp;', 'filler');
     464              }
     465              return $output;
     466          }
     467  
     468          $completionicon = '';
     469  
     470          if ($isediting || !$istrackeduser) {
     471              switch ($completion) {
     472                  case COMPLETION_TRACKING_MANUAL :
     473                      $completionicon = 'manual-enabled'; break;
     474                  case COMPLETION_TRACKING_AUTOMATIC :
     475                      $completionicon = 'auto-enabled'; break;
     476              }
     477          } else {
     478              $completiondata = $completioninfo->get_data($mod, true);
     479              if ($completion == COMPLETION_TRACKING_MANUAL) {
     480                  switch($completiondata->completionstate) {
     481                      case COMPLETION_INCOMPLETE:
     482                          $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
     483                          break;
     484                      case COMPLETION_COMPLETE:
     485                          $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
     486                          break;
     487                  }
     488              } else { // Automatic
     489                  switch($completiondata->completionstate) {
     490                      case COMPLETION_INCOMPLETE:
     491                          $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
     492                          break;
     493                      case COMPLETION_COMPLETE:
     494                          $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
     495                          break;
     496                      case COMPLETION_COMPLETE_PASS:
     497                          $completionicon = 'auto-pass'; break;
     498                      case COMPLETION_COMPLETE_FAIL:
     499                          $completionicon = 'auto-fail'; break;
     500                  }
     501              }
     502          }
     503          if ($completionicon) {
     504              $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
     505              if (!$isediting && $istrackeduser && $completiondata->overrideby) {
     506                  $args = new stdClass();
     507                  $args->modname = $formattedname;
     508                  $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
     509                  $args->overrideuser = fullname($overridebyuser);
     510                  $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
     511              } else {
     512                  $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
     513              }
     514  
     515              if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
     516                  // When editing, the icon is just an image.
     517                  $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
     518                          array('title' => $imgalt, 'class' => 'iconsmall'));
     519                  $output .= html_writer::tag('span', $this->output->render($completionpixicon),
     520                          array('class' => 'autocompletion'));
     521              } else if ($completion == COMPLETION_TRACKING_MANUAL) {
     522                  $newstate =
     523                      $completiondata->completionstate == COMPLETION_COMPLETE
     524                      ? COMPLETION_INCOMPLETE
     525                      : COMPLETION_COMPLETE;
     526                  // In manual mode the icon is a toggle form...
     527  
     528                  // If this completion state is used by the
     529                  // conditional activities system, we need to turn
     530                  // off the JS.
     531                  $extraclass = '';
     532                  if (!empty($CFG->enableavailability) &&
     533                          core_availability\info::completion_value_used($course, $mod->id)) {
     534                      $extraclass = ' preventjs';
     535                  }
     536                  $output .= html_writer::start_tag('form', array('method' => 'post',
     537                      'action' => new moodle_url('/course/togglecompletion.php'),
     538                      'class' => 'togglecompletion'. $extraclass));
     539                  $output .= html_writer::start_tag('div');
     540                  $output .= html_writer::empty_tag('input', array(
     541                      'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
     542                  $output .= html_writer::empty_tag('input', array(
     543                      'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
     544                  $output .= html_writer::empty_tag('input', array(
     545                      'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
     546                  $output .= html_writer::empty_tag('input', array(
     547                      'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
     548                  $output .= html_writer::tag('button',
     549                      $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
     550                          array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
     551                  $output .= html_writer::end_tag('div');
     552                  $output .= html_writer::end_tag('form');
     553              } else {
     554                  // In auto mode, the icon is just an image.
     555                  $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
     556                          array('title' => $imgalt));
     557                  $output .= html_writer::tag('span', $this->output->render($completionpixicon),
     558                          array('class' => 'autocompletion'));
     559              }
     560          }
     561          return $output;
     562      }
     563  
     564      /**
     565       * Checks if course module has any conditions that may make it unavailable for
     566       * all or some of the students
     567       *
     568       * This function is internal and is only used to create CSS classes for the module name/text
     569       *
     570       * @param cm_info $mod
     571       * @return bool
     572       */
     573      protected function is_cm_conditionally_hidden(cm_info $mod) {
     574          global $CFG;
     575          $conditionalhidden = false;
     576          if (!empty($CFG->enableavailability)) {
     577              $info = new \core_availability\info_module($mod);
     578              $conditionalhidden = !$info->is_available_for_all();
     579          }
     580          return $conditionalhidden;
     581      }
     582  
     583      /**
     584       * Renders html to display a name with the link to the course module on a course page
     585       *
     586       * If module is unavailable for user but still needs to be displayed
     587       * in the list, just the name is returned without a link
     588       *
     589       * Note, that for course modules that never have separate pages (i.e. labels)
     590       * this function return an empty string
     591       *
     592       * @param cm_info $mod
     593       * @param array $displayoptions
     594       * @return string
     595       */
     596      public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
     597          if (!$mod->is_visible_on_course_page() || !$mod->url) {
     598              // Nothing to be displayed to the user.
     599              return '';
     600          }
     601  
     602          list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
     603          $groupinglabel = $mod->get_grouping_label($textclasses);
     604  
     605          // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
     606          // to get the display title of the activity.
     607          $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
     608          return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
     609              $groupinglabel;
     610      }
     611  
     612      /**
     613       * Returns the CSS classes for the activity name/content
     614       *
     615       * For items which are hidden, unavailable or stealth but should be displayed
     616       * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
     617       * Students will also see as dimmed activities names that are not yet available
     618       * but should still be displayed (without link) with availability info.
     619       *
     620       * @param cm_info $mod
     621       * @return array array of two elements ($linkclasses, $textclasses)
     622       */
     623      protected function course_section_cm_classes(cm_info $mod) {
     624          $linkclasses = '';
     625          $textclasses = '';
     626          if ($mod->uservisible) {
     627              $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
     628              $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
     629                  has_capability('moodle/course:viewhiddenactivities', $mod->context);
     630              if ($accessiblebutdim) {
     631                  $linkclasses .= ' dimmed';
     632                  $textclasses .= ' dimmed_text';
     633                  if ($conditionalhidden) {
     634                      $linkclasses .= ' conditionalhidden';
     635                      $textclasses .= ' conditionalhidden';
     636                  }
     637              }
     638              if ($mod->is_stealth()) {
     639                  // Stealth activity is the one that is not visible on course page.
     640                  // It still may be displayed to the users who can manage it.
     641                  $linkclasses .= ' stealth';
     642                  $textclasses .= ' stealth';
     643              }
     644          } else {
     645              $linkclasses .= ' dimmed';
     646              $textclasses .= ' dimmed dimmed_text';
     647          }
     648          return array($linkclasses, $textclasses);
     649      }
     650  
     651      /**
     652       * Renders html to display a name with the link to the course module on a course page
     653       *
     654       * If module is unavailable for user but still needs to be displayed
     655       * in the list, just the name is returned without a link
     656       *
     657       * Note, that for course modules that never have separate pages (i.e. labels)
     658       * this function return an empty string
     659       *
     660       * @param cm_info $mod
     661       * @param array $displayoptions
     662       * @return string
     663       */
     664      public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
     665          $output = '';
     666          $url = $mod->url;
     667          if (!$mod->is_visible_on_course_page() || !$url) {
     668              // Nothing to be displayed to the user.
     669              return $output;
     670          }
     671  
     672          //Accessibility: for files get description via icon, this is very ugly hack!
     673          $instancename = $mod->get_formatted_name();
     674          $altname = $mod->modfullname;
     675          // Avoid unnecessary duplication: if e.g. a forum name already
     676          // includes the word forum (or Forum, etc) then it is unhelpful
     677          // to include that in the accessible description that is added.
     678          if (false !== strpos(core_text::strtolower($instancename),
     679                  core_text::strtolower($altname))) {
     680              $altname = '';
     681          }
     682          // File type after name, for alphabetic lists (screen reader).
     683          if ($altname) {
     684              $altname = get_accesshide(' '.$altname);
     685          }
     686  
     687          list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
     688  
     689          // Get on-click attribute value if specified and decode the onclick - it
     690          // has already been encoded for display (puke).
     691          $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
     692  
     693          // Display link itself.
     694          $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
     695                  'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
     696                  html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
     697          if ($mod->uservisible) {
     698              $output .= html_writer::link($url, $activitylink, array('class' => 'aalink' . $linkclasses, 'onclick' => $onclick));
     699          } else {
     700              // We may be displaying this just in order to show information
     701              // about visibility, without the actual link ($mod->is_visible_on_course_page()).
     702              $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
     703          }
     704          return $output;
     705      }
     706  
     707      /**
     708       * Renders html to display the module content on the course page (i.e. text of the labels)
     709       *
     710       * @param cm_info $mod
     711       * @param array $displayoptions
     712       * @return string
     713       */
     714      public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
     715          $output = '';
     716          if (!$mod->is_visible_on_course_page()) {
     717              // nothing to be displayed to the user
     718              return $output;
     719          }
     720          $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
     721          list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
     722          if ($mod->url && $mod->uservisible) {
     723              if ($content) {
     724                  // If specified, display extra content after link.
     725                  $output = html_writer::tag('div', $content, array('class' =>
     726                          trim('contentafterlink ' . $textclasses)));
     727              }
     728          } else {
     729              $groupinglabel = $mod->get_grouping_label($textclasses);
     730  
     731              // No link, so display only content.
     732              $output = html_writer::tag('div', $content . $groupinglabel,
     733                      array('class' => 'contentwithoutlink ' . $textclasses));
     734          }
     735          return $output;
     736      }
     737  
     738      /**
     739       * Displays availability info for a course section or course module
     740       *
     741       * @param string $text
     742       * @param string $additionalclasses
     743       * @return string
     744       */
     745      public function availability_info($text, $additionalclasses = '') {
     746  
     747          $data = ['text' => $text, 'classes' => $additionalclasses];
     748          $additionalclasses = array_filter(explode(' ', $additionalclasses));
     749  
     750          if (in_array('ishidden', $additionalclasses)) {
     751              $data['ishidden'] = 1;
     752  
     753          } else if (in_array('isstealth', $additionalclasses)) {
     754              $data['isstealth'] = 1;
     755  
     756          } else if (in_array('isrestricted', $additionalclasses)) {
     757              $data['isrestricted'] = 1;
     758  
     759              if (in_array('isfullinfo', $additionalclasses)) {
     760                  $data['isfullinfo'] = 1;
     761              }
     762          }
     763  
     764          return $this->render_from_template('core/availability_info', $data);
     765      }
     766  
     767      /**
     768       * Renders HTML to show course module availability information (for someone who isn't allowed
     769       * to see the activity itself, or for staff)
     770       *
     771       * @param cm_info $mod
     772       * @param array $displayoptions
     773       * @return string
     774       */
     775      public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
     776          global $CFG;
     777          $output = '';
     778          if (!$mod->is_visible_on_course_page()) {
     779              return $output;
     780          }
     781          if (!$mod->uservisible) {
     782              // this is a student who is not allowed to see the module but might be allowed
     783              // to see availability info (i.e. "Available from ...")
     784              if (!empty($mod->availableinfo)) {
     785                  $formattedinfo = \core_availability\info::format_info(
     786                          $mod->availableinfo, $mod->get_course());
     787                  $output = $this->availability_info($formattedinfo, 'isrestricted');
     788              }
     789              return $output;
     790          }
     791          // this is a teacher who is allowed to see module but still should see the
     792          // information that module is not available to all/some students
     793          $modcontext = context_module::instance($mod->id);
     794          $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
     795          if ($canviewhidden && !$mod->visible) {
     796              // This module is hidden but current user has capability to see it.
     797              // Do not display the availability info if the whole section is hidden.
     798              if ($mod->get_section_info()->visible) {
     799                  $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
     800              }
     801          } else if ($mod->is_stealth()) {
     802              // This module is available but is normally not displayed on the course page
     803              // (this user can see it because they can manage it).
     804              $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
     805          }
     806          if ($canviewhidden && !empty($CFG->enableavailability)) {
     807              // Display information about conditional availability.
     808              // Don't add availability information if user is not editing and activity is hidden.
     809              if ($mod->visible || $this->page->user_is_editing()) {
     810                  $hidinfoclass = 'isrestricted isfullinfo';
     811                  if (!$mod->visible) {
     812                      $hidinfoclass .= ' hide';
     813                  }
     814                  $ci = new \core_availability\info_module($mod);
     815                  $fullinfo = $ci->get_full_information();
     816                  if ($fullinfo) {
     817                      $formattedinfo = \core_availability\info::format_info(
     818                              $fullinfo, $mod->get_course());
     819                      $output .= $this->availability_info($formattedinfo, $hidinfoclass);
     820                  }
     821              }
     822          }
     823          return $output;
     824      }
     825  
     826      /**
     827       * Renders HTML to display one course module for display within a section.
     828       *
     829       * This function calls:
     830       * {@link core_course_renderer::course_section_cm()}
     831       *
     832       * @param stdClass $course
     833       * @param completion_info $completioninfo
     834       * @param cm_info $mod
     835       * @param int|null $sectionreturn
     836       * @param array $displayoptions
     837       * @return String
     838       */
     839      public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
     840          $output = '';
     841          if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
     842              $infoclass = '';
     843              if ((($course->enablecompletion == COMPLETION_ENABLED) &&
     844                  ($course->showcompletionconditions == COMPLETION_SHOW_CONDITIONS)) || !empty($course->showactivitydates)) {
     845                  // This will apply styles to the course homepage when the activity information output component is displayed.
     846                  $infoclass = 'hasinfo';
     847              }
     848              $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses . ' ' . $infoclass;
     849              $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
     850          }
     851          return $output;
     852      }
     853  
     854      /**
     855       * Renders HTML to display one course module in a course section
     856       *
     857       * This includes link, content, availability, completion info and additional information
     858       * that module type wants to display (i.e. number of unread forum posts)
     859       *
     860       * This function calls:
     861       * {@link core_course_renderer::course_section_cm_name()}
     862       * {@link core_course_renderer::course_section_cm_text()}
     863       * {@link core_course_renderer::course_section_cm_availability()}
     864       * {@link course_get_cm_edit_actions()}
     865       * {@link core_course_renderer::course_section_cm_edit_actions()}
     866       *
     867       * @param stdClass $course
     868       * @param completion_info $completioninfo
     869       * @param cm_info $mod
     870       * @param int|null $sectionreturn
     871       * @param array $displayoptions
     872       * @return string
     873       */
     874      public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
     875          global $USER;
     876  
     877          $output = '';
     878          // We return empty string (because course module will not be displayed at all)
     879          // if:
     880          // 1) The activity is not visible to users
     881          // and
     882          // 2) The 'availableinfo' is empty, i.e. the activity was
     883          //     hidden in a way that leaves no info, such as using the
     884          //     eye icon.
     885          if (!$mod->is_visible_on_course_page()) {
     886              return $output;
     887          }
     888  
     889          $indentclasses = 'mod-indent';
     890          if (!empty($mod->indent)) {
     891              $indentclasses .= ' mod-indent-'.$mod->indent;
     892              if ($mod->indent > 15) {
     893                  $indentclasses .= ' mod-indent-huge';
     894              }
     895          }
     896  
     897          $output .= html_writer::start_tag('div');
     898  
     899          if ($this->page->user_is_editing()) {
     900              $output .= course_get_cm_move($mod, $sectionreturn);
     901          }
     902  
     903          $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer w-100'));
     904  
     905          // This div is used to indent the content.
     906          $output .= html_writer::div('', $indentclasses);
     907  
     908          // Start a wrapper for the actual content to keep the indentation consistent
     909          $output .= html_writer::start_tag('div');
     910  
     911          // Display the link to the module (or do nothing if module has no url)
     912          $cmname = $this->course_section_cm_name($mod, $displayoptions);
     913  
     914          if (!empty($cmname)) {
     915              // Start the div for the activity title, excluding the edit icons.
     916              $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
     917              $output .= $cmname;
     918  
     919  
     920              // Module can put text after the link (e.g. forum unread)
     921              $output .= $mod->afterlink;
     922  
     923              // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
     924              $output .= html_writer::end_tag('div'); // .activityinstance
     925          }
     926  
     927          // If there is content but NO link (eg label), then display the
     928          // content here (BEFORE any icons). In this case cons must be
     929          // displayed after the content so that it makes more sense visually
     930          // and for accessibility reasons, e.g. if you have a one-line label
     931          // it should work similarly (at least in terms of ordering) to an
     932          // activity.
     933          $contentpart = $this->course_section_cm_text($mod, $displayoptions);
     934          $url = $mod->url;
     935          if (empty($url)) {
     936              $output .= $contentpart;
     937          }
     938  
     939          $modicons = '';
     940          if ($this->page->user_is_editing()) {
     941              $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
     942              $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
     943              $modicons .= $mod->afterediticons;
     944          }
     945  
     946          if (!empty($modicons)) {
     947              $output .= html_writer::div($modicons, 'actions');
     948          }
     949  
     950          // Fetch completion details.
     951          $showcompletionconditions = $course->showcompletionconditions == COMPLETION_SHOW_CONDITIONS;
     952          $completiondetails = \core_completion\cm_completion_details::get_instance($mod, $USER->id, $showcompletionconditions);
     953          $ismanualcompletion = $completiondetails->has_completion() && !$completiondetails->is_automatic();
     954  
     955          // Fetch activity dates.
     956          $activitydates = [];
     957          if ($course->showactivitydates) {
     958              $activitydates = \core\activity_dates::get_dates_for_module($mod, $USER->id);
     959          }
     960  
     961          // Show the activity information if:
     962          // - The course's showcompletionconditions setting is enabled; or
     963          // - The activity tracks completion manually; or
     964          // - There are activity dates to be shown.
     965          if ($showcompletionconditions || $ismanualcompletion || $activitydates) {
     966              $output .= $this->output->activity_information($mod, $completiondetails, $activitydates);
     967          }
     968  
     969          // Show availability info (if module is not available).
     970          $output .= $this->course_section_cm_availability($mod, $displayoptions);
     971  
     972          // If there is content AND a link, then display the content here
     973          // (AFTER any icons). Otherwise it was displayed before
     974          if (!empty($url)) {
     975              $output .= $contentpart;
     976          }
     977  
     978          $output .= html_writer::end_tag('div'); // $indentclasses
     979  
     980          // End of indentation div.
     981          $output .= html_writer::end_tag('div');
     982  
     983          $output .= html_writer::end_tag('div');
     984          return $output;
     985      }
     986  
     987      /**
     988       * Message displayed to the user when they try to access unavailable activity following URL
     989       *
     990       * This method is a very simplified version of {@link course_section_cm()} to be part of the error
     991       * notification only. It also does not check if module is visible on course page or not.
     992       *
     993       * The message will be displayed inside notification!
     994       *
     995       * @param cm_info $cm
     996       * @return string
     997       */
     998      public function course_section_cm_unavailable_error_message(cm_info $cm) {
     999          if ($cm->uservisible) {
    1000              return null;
    1001          }
    1002          if (!$cm->availableinfo) {
    1003              return get_string('activityiscurrentlyhidden');
    1004          }
    1005  
    1006          $altname = get_accesshide(' ' . $cm->modfullname);
    1007          $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
    1008                  'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
    1009              html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
    1010          $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
    1011          return html_writer::div($name, 'activityinstance-error') .
    1012          html_writer::div($formattedinfo, 'availabilityinfo-error');
    1013      }
    1014  
    1015      /**
    1016       * Renders HTML to display a list of course modules in a course section
    1017       * Also displays "move here" controls in Javascript-disabled mode
    1018       *
    1019       * This function calls {@link core_course_renderer::course_section_cm()}
    1020       *
    1021       * @param stdClass $course course object
    1022       * @param int|stdClass|section_info $section relative section number or section object
    1023       * @param int $sectionreturn section number to return to
    1024       * @param int $displayoptions
    1025       * @return void
    1026       */
    1027      public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
    1028          global $USER;
    1029  
    1030          $output = '';
    1031          $modinfo = get_fast_modinfo($course);
    1032          if (is_object($section)) {
    1033              $section = $modinfo->get_section_info($section->section);
    1034          } else {
    1035              $section = $modinfo->get_section_info($section);
    1036          }
    1037          $completioninfo = new completion_info($course);
    1038  
    1039          // check if we are currently in the process of moving a module with JavaScript disabled
    1040          $ismoving = $this->page->user_is_editing() && ismoving($course->id);
    1041          if ($ismoving) {
    1042              $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
    1043          }
    1044  
    1045          // Get the list of modules visible to user (excluding the module being moved if there is one)
    1046          $moduleshtml = array();
    1047          if (!empty($modinfo->sections[$section->section])) {
    1048              foreach ($modinfo->sections[$section->section] as $modnumber) {
    1049                  $mod = $modinfo->cms[$modnumber];
    1050  
    1051                  if ($ismoving and $mod->id == $USER->activitycopy) {
    1052                      // do not display moving mod
    1053                      continue;
    1054                  }
    1055  
    1056                  if ($modulehtml = $this->course_section_cm_list_item($course,
    1057                          $completioninfo, $mod, $sectionreturn, $displayoptions)) {
    1058                      $moduleshtml[$modnumber] = $modulehtml;
    1059                  }
    1060              }
    1061          }
    1062  
    1063          $sectionoutput = '';
    1064          if (!empty($moduleshtml) || $ismoving) {
    1065              foreach ($moduleshtml as $modnumber => $modulehtml) {
    1066                  if ($ismoving) {
    1067                      $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
    1068                      $sectionoutput .= html_writer::tag('li',
    1069                              html_writer::link($movingurl, '', array('title' => $strmovefull, 'class' => 'movehere')),
    1070                              array('class' => 'movehere'));
    1071                  }
    1072  
    1073                  $sectionoutput .= $modulehtml;
    1074              }
    1075  
    1076              if ($ismoving) {
    1077                  $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
    1078                  $sectionoutput .= html_writer::tag('li',
    1079                          html_writer::link($movingurl, '', array('title' => $strmovefull, 'class' => 'movehere')),
    1080                          array('class' => 'movehere'));
    1081              }
    1082          }
    1083  
    1084          // Always output the section module list.
    1085          $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
    1086  
    1087          return $output;
    1088      }
    1089  
    1090      /**
    1091       * Displays a custom list of courses with paging bar if necessary
    1092       *
    1093       * If $paginationurl is specified but $totalcount is not, the link 'View more'
    1094       * appears under the list.
    1095       *
    1096       * If both $paginationurl and $totalcount are specified, and $totalcount is
    1097       * bigger than count($courses), a paging bar is displayed above and under the
    1098       * courses list.
    1099       *
    1100       * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
    1101       * @param bool $showcategoryname whether to add category name to the course description
    1102       * @param string $additionalclasses additional CSS classes to add to the div.courses
    1103       * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
    1104       * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
    1105       * @param int $page current page number (defaults to 0 referring to the first page)
    1106       * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
    1107       * @return string
    1108       */
    1109      public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
    1110          global $CFG;
    1111          // create instance of coursecat_helper to pass display options to function rendering courses list
    1112          $chelper = new coursecat_helper();
    1113          if ($showcategoryname) {
    1114              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
    1115          } else {
    1116              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
    1117          }
    1118          if ($totalcount !== null && $paginationurl !== null) {
    1119              // add options to display pagination
    1120              if ($perpage === null) {
    1121                  $perpage = $CFG->coursesperpage;
    1122              }
    1123              $chelper->set_courses_display_options(array(
    1124                  'limit' => $perpage,
    1125                  'offset' => ((int)$page) * $perpage,
    1126                  'paginationurl' => $paginationurl,
    1127              ));
    1128          } else if ($paginationurl !== null) {
    1129              // add options to display 'View more' link
    1130              $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
    1131              $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
    1132          }
    1133          $chelper->set_attributes(array('class' => $additionalclasses));
    1134          $content = $this->coursecat_courses($chelper, $courses, $totalcount);
    1135          return $content;
    1136      }
    1137  
    1138      /**
    1139       * Returns HTML to display course name.
    1140       *
    1141       * @param coursecat_helper $chelper
    1142       * @param core_course_list_element $course
    1143       * @return string
    1144       */
    1145      protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
    1146          $content = '';
    1147          if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
    1148              $nametag = 'h3';
    1149          } else {
    1150              $nametag = 'div';
    1151          }
    1152          $coursename = $chelper->get_course_formatted_name($course);
    1153          $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
    1154              $coursename, ['class' => $course->visible ? 'aalink' : 'aalink dimmed']);
    1155          $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
    1156          // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
    1157          $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
    1158          if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
    1159              if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
    1160                  || $course->has_custom_fields()) {
    1161                  $url = new moodle_url('/course/info.php', ['id' => $course->id]);
    1162                  $image = $this->output->pix_icon('i/info', $this->strings->summary);
    1163                  $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
    1164                  // Make sure JS file to expand course content is included.
    1165                  $this->coursecat_include_js();
    1166              }
    1167          }
    1168          $content .= html_writer::end_tag('div');
    1169          return $content;
    1170      }
    1171  
    1172      /**
    1173       * Returns HTML to display course enrolment icons.
    1174       *
    1175       * @param core_course_list_element $course
    1176       * @return string
    1177       */
    1178      protected function course_enrolment_icons(core_course_list_element $course): string {
    1179          $content = '';
    1180          if ($icons = enrol_get_course_info_icons($course)) {
    1181              $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
    1182              foreach ($icons as $icon) {
    1183                  $content .= $this->render($icon);
    1184              }
    1185              $content .= html_writer::end_tag('div');
    1186          }
    1187          return $content;
    1188      }
    1189  
    1190      /**
    1191       * Displays one course in the list of courses.
    1192       *
    1193       * This is an internal function, to display an information about just one course
    1194       * please use {@link core_course_renderer::course_info_box()}
    1195       *
    1196       * @param coursecat_helper $chelper various display options
    1197       * @param core_course_list_element|stdClass $course
    1198       * @param string $additionalclasses additional classes to add to the main <div> tag (usually
    1199       *    depend on the course position in list - first/last/even/odd)
    1200       * @return string
    1201       */
    1202      protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
    1203          if (!isset($this->strings->summary)) {
    1204              $this->strings->summary = get_string('summary');
    1205          }
    1206          if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
    1207              return '';
    1208          }
    1209          if ($course instanceof stdClass) {
    1210              $course = new core_course_list_element($course);
    1211          }
    1212          $content = '';
    1213          $classes = trim('coursebox clearfix '. $additionalclasses);
    1214          if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
    1215              $classes .= ' collapsed';
    1216          }
    1217  
    1218          // .coursebox
    1219          $content .= html_writer::start_tag('div', array(
    1220              'class' => $classes,
    1221              'data-courseid' => $course->id,
    1222              'data-type' => self::COURSECAT_TYPE_COURSE,
    1223          ));
    1224  
    1225          $content .= html_writer::start_tag('div', array('class' => 'info'));
    1226          $content .= $this->course_name($chelper, $course);
    1227          $content .= $this->course_enrolment_icons($course);
    1228          $content .= html_writer::end_tag('div');
    1229  
    1230          $content .= html_writer::start_tag('div', array('class' => 'content'));
    1231          $content .= $this->coursecat_coursebox_content($chelper, $course);
    1232          $content .= html_writer::end_tag('div');
    1233  
    1234          $content .= html_writer::end_tag('div'); // .coursebox
    1235          return $content;
    1236      }
    1237  
    1238      /**
    1239       * Returns HTML to display course summary.
    1240       *
    1241       * @param coursecat_helper $chelper
    1242       * @param core_course_list_element $course
    1243       * @return string
    1244       */
    1245      protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
    1246          $content = '';
    1247          if ($course->has_summary()) {
    1248              $content .= html_writer::start_tag('div', ['class' => 'summary']);
    1249              $content .= $chelper->get_course_formatted_summary($course,
    1250                  array('overflowdiv' => true, 'noclean' => true, 'para' => false));
    1251              $content .= html_writer::end_tag('div');
    1252          }
    1253          return $content;
    1254      }
    1255  
    1256      /**
    1257       * Returns HTML to display course contacts.
    1258       *
    1259       * @param core_course_list_element $course
    1260       * @return string
    1261       */
    1262      protected function course_contacts(core_course_list_element $course) {
    1263          $content = '';
    1264          if ($course->has_course_contacts()) {
    1265              $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
    1266              foreach ($course->get_course_contacts() as $coursecontact) {
    1267                  $rolenames = array_map(function ($role) {
    1268                      return $role->displayname;
    1269                  }, $coursecontact['roles']);
    1270                  $name = implode(", ", $rolenames).': '.
    1271                      html_writer::link(new moodle_url('/user/view.php',
    1272                          ['id' => $coursecontact['user']->id, 'course' => SITEID]),
    1273                          $coursecontact['username']);
    1274                  $content .= html_writer::tag('li', $name);
    1275              }
    1276              $content .= html_writer::end_tag('ul');
    1277          }
    1278          return $content;
    1279      }
    1280  
    1281      /**
    1282       * Returns HTML to display course overview files.
    1283       *
    1284       * @param core_course_list_element $course
    1285       * @return string
    1286       */
    1287      protected function course_overview_files(core_course_list_element $course): string {
    1288          global $CFG;
    1289  
    1290          $contentimages = $contentfiles = '';
    1291          foreach ($course->get_course_overviewfiles() as $file) {
    1292              $isimage = $file->is_valid_image();
    1293              $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
    1294                  '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
    1295                  $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
    1296              if ($isimage) {
    1297                  $contentimages .= html_writer::tag('div',
    1298                      html_writer::empty_tag('img', ['src' => $url]),
    1299                      ['class' => 'courseimage']);
    1300              } else {
    1301                  $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
    1302                  $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
    1303                      html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
    1304                  $contentfiles .= html_writer::tag('span',
    1305                      html_writer::link($url, $filename),
    1306                      ['class' => 'coursefile fp-filename-icon']);
    1307              }
    1308          }
    1309          return $contentimages . $contentfiles;
    1310      }
    1311  
    1312      /**
    1313       * Returns HTML to display course category name.
    1314       *
    1315       * @param coursecat_helper $chelper
    1316       * @param core_course_list_element $course
    1317       * @return string
    1318       */
    1319      protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
    1320          $content = '';
    1321          // Display course category if necessary (for example in search results).
    1322          if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
    1323              if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
    1324                  $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
    1325                  $content .= get_string('category').': '.
    1326                      html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
    1327                          $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
    1328                  $content .= html_writer::end_tag('div');
    1329              }
    1330          }
    1331          return $content;
    1332      }
    1333  
    1334      /**
    1335       * Returns HTML to display course custom fields.
    1336       *
    1337       * @param core_course_list_element $course
    1338       * @return string
    1339       */
    1340      protected function course_custom_fields(core_course_list_element $course): string {
    1341          $content = '';
    1342          if ($course->has_custom_fields()) {
    1343              $handler = core_course\customfield\course_handler::create();
    1344              $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
    1345              $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
    1346          }
    1347          return $content;
    1348      }
    1349  
    1350      /**
    1351       * Returns HTML to display course content (summary, course contacts and optionally category name)
    1352       *
    1353       * This method is called from coursecat_coursebox() and may be re-used in AJAX
    1354       *
    1355       * @param coursecat_helper $chelper various display options
    1356       * @param stdClass|core_course_list_element $course
    1357       * @return string
    1358       */
    1359      protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
    1360          if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
    1361              return '';
    1362          }
    1363          if ($course instanceof stdClass) {
    1364              $course = new core_course_list_element($course);
    1365          }
    1366          $content = $this->course_summary($chelper, $course);
    1367          $content .= $this->course_overview_files($course);
    1368          $content .= $this->course_contacts($course);
    1369          $content .= $this->course_category_name($chelper, $course);
    1370          $content .= $this->course_custom_fields($course);
    1371          return $content;
    1372      }
    1373  
    1374      /**
    1375       * Renders the list of courses
    1376       *
    1377       * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
    1378       * method from outside of the class
    1379       *
    1380       * If list of courses is specified in $courses; the argument $chelper is only used
    1381       * to retrieve display options and attributes, only methods get_show_courses(),
    1382       * get_courses_display_option() and get_and_erase_attributes() are called.
    1383       *
    1384       * @param coursecat_helper $chelper various display options
    1385       * @param array $courses the list of courses to display
    1386       * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
    1387       *     defaulted to count($courses)
    1388       * @return string
    1389       */
    1390      protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
    1391          global $CFG;
    1392          if ($totalcount === null) {
    1393              $totalcount = count($courses);
    1394          }
    1395          if (!$totalcount) {
    1396              // Courses count is cached during courses retrieval.
    1397              return '';
    1398          }
    1399  
    1400          if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
    1401              // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
    1402              if ($totalcount <= $CFG->courseswithsummarieslimit) {
    1403                  $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
    1404              } else {
    1405                  $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
    1406              }
    1407          }
    1408  
    1409          // prepare content of paging bar if it is needed
    1410          $paginationurl = $chelper->get_courses_display_option('paginationurl');
    1411          $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
    1412          if ($totalcount > count($courses)) {
    1413              // there are more results that can fit on one page
    1414              if ($paginationurl) {
    1415                  // the option paginationurl was specified, display pagingbar
    1416                  $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
    1417                  $page = $chelper->get_courses_display_option('offset') / $perpage;
    1418                  $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
    1419                          $paginationurl->out(false, array('perpage' => $perpage)));
    1420                  if ($paginationallowall) {
    1421                      $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
    1422                              get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
    1423                  }
    1424              } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
    1425                  // the option for 'View more' link was specified, display more link
    1426                  $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
    1427                  $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
    1428                          array('class' => 'paging paging-morelink'));
    1429              }
    1430          } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
    1431              // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
    1432              $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
    1433                  get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
    1434          }
    1435  
    1436          // display list of courses
    1437          $attributes = $chelper->get_and_erase_attributes('courses');
    1438          $content = html_writer::start_tag('div', $attributes);
    1439  
    1440          if (!empty($pagingbar)) {
    1441              $content .= $pagingbar;
    1442          }
    1443  
    1444          $coursecount = 0;
    1445          foreach ($courses as $course) {
    1446              $coursecount ++;
    1447              $classes = ($coursecount%2) ? 'odd' : 'even';
    1448              if ($coursecount == 1) {
    1449                  $classes .= ' first';
    1450              }
    1451              if ($coursecount >= count($courses)) {
    1452                  $classes .= ' last';
    1453              }
    1454              $content .= $this->coursecat_coursebox($chelper, $course, $classes);
    1455          }
    1456  
    1457          if (!empty($pagingbar)) {
    1458              $content .= $pagingbar;
    1459          }
    1460          if (!empty($morelink)) {
    1461              $content .= $morelink;
    1462          }
    1463  
    1464          $content .= html_writer::end_tag('div'); // .courses
    1465          return $content;
    1466      }
    1467  
    1468      /**
    1469       * Renders the list of subcategories in a category
    1470       *
    1471       * @param coursecat_helper $chelper various display options
    1472       * @param core_course_category $coursecat
    1473       * @param int $depth depth of the category in the current tree
    1474       * @return string
    1475       */
    1476      protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
    1477          global $CFG;
    1478          $subcategories = array();
    1479          if (!$chelper->get_categories_display_option('nodisplay')) {
    1480              $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
    1481          }
    1482          $totalcount = $coursecat->get_children_count();
    1483          if (!$totalcount) {
    1484              // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
    1485              // to avoid extra DB requests.
    1486              // Categories count is cached during children categories retrieval.
    1487              return '';
    1488          }
    1489  
    1490          // prepare content of paging bar or more link if it is needed
    1491          $paginationurl = $chelper->get_categories_display_option('paginationurl');
    1492          $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
    1493          if ($totalcount > count($subcategories)) {
    1494              if ($paginationurl) {
    1495                  // the option 'paginationurl was specified, display pagingbar
    1496                  $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
    1497                  $page = $chelper->get_categories_display_option('offset') / $perpage;
    1498                  $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
    1499                          $paginationurl->out(false, array('perpage' => $perpage)));
    1500                  if ($paginationallowall) {
    1501                      $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
    1502                              get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
    1503                  }
    1504              } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
    1505                  // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
    1506                  if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
    1507                      $viewmoreurl->param('categoryid', $coursecat->id);
    1508                  }
    1509                  $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
    1510                  $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
    1511                          array('class' => 'paging paging-morelink'));
    1512              }
    1513          } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
    1514              // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
    1515              $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
    1516                  get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
    1517          }
    1518  
    1519          // display list of subcategories
    1520          $content = html_writer::start_tag('div', array('class' => 'subcategories'));
    1521  
    1522          if (!empty($pagingbar)) {
    1523              $content .= $pagingbar;
    1524          }
    1525  
    1526          foreach ($subcategories as $subcategory) {
    1527              $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
    1528          }
    1529  
    1530          if (!empty($pagingbar)) {
    1531              $content .= $pagingbar;
    1532          }
    1533          if (!empty($morelink)) {
    1534              $content .= $morelink;
    1535          }
    1536  
    1537          $content .= html_writer::end_tag('div');
    1538          return $content;
    1539      }
    1540  
    1541      /**
    1542       * Make sure that javascript file for AJAX expanding of courses and categories content is included
    1543       */
    1544      protected function coursecat_include_js() {
    1545          if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
    1546              return;
    1547          }
    1548  
    1549          // We must only load this module once.
    1550          $this->page->requires->yui_module('moodle-course-categoryexpander',
    1551                  'Y.Moodle.course.categoryexpander.init');
    1552      }
    1553  
    1554      /**
    1555       * Returns HTML to display the subcategories and courses in the given category
    1556       *
    1557       * This method is re-used by AJAX to expand content of not loaded category
    1558       *
    1559       * @param coursecat_helper $chelper various display options
    1560       * @param core_course_category $coursecat
    1561       * @param int $depth depth of the category in the current tree
    1562       * @return string
    1563       */
    1564      protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
    1565          $content = '';
    1566          // Subcategories
    1567          $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
    1568  
    1569          // AUTO show courses: Courses will be shown expanded if this is not nested category,
    1570          // and number of courses no bigger than $CFG->courseswithsummarieslimit.
    1571          $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
    1572          if ($showcoursesauto && $depth) {
    1573              // this is definitely collapsed mode
    1574              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
    1575          }
    1576  
    1577          // Courses
    1578          if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
    1579              $courses = array();
    1580              if (!$chelper->get_courses_display_option('nodisplay')) {
    1581                  $courses = $coursecat->get_courses($chelper->get_courses_display_options());
    1582              }
    1583              if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
    1584                  // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
    1585                  if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
    1586                      $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
    1587                  }
    1588              }
    1589              $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
    1590          }
    1591  
    1592          if ($showcoursesauto) {
    1593              // restore the show_courses back to AUTO
    1594              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
    1595          }
    1596  
    1597          return $content;
    1598      }
    1599  
    1600      /**
    1601       * Returns HTML to display a course category as a part of a tree
    1602       *
    1603       * This is an internal function, to display a particular category and all its contents
    1604       * use {@link core_course_renderer::course_category()}
    1605       *
    1606       * @param coursecat_helper $chelper various display options
    1607       * @param core_course_category $coursecat
    1608       * @param int $depth depth of this category in the current tree
    1609       * @return string
    1610       */
    1611      protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
    1612          // open category tag
    1613          $classes = array('category');
    1614          if (empty($coursecat->visible)) {
    1615              $classes[] = 'dimmed_category';
    1616          }
    1617          if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
    1618              // do not load content
    1619              $categorycontent = '';
    1620              $classes[] = 'notloaded';
    1621              if ($coursecat->get_children_count() ||
    1622                      ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
    1623                  $classes[] = 'with_children';
    1624                  $classes[] = 'collapsed';
    1625              }
    1626          } else {
    1627              // load category content
    1628              $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
    1629              $classes[] = 'loaded';
    1630              if (!empty($categorycontent)) {
    1631                  $classes[] = 'with_children';
    1632                  // Category content loaded with children.
    1633                  $this->categoryexpandedonload = true;
    1634              }
    1635          }
    1636  
    1637          // Make sure JS file to expand category content is included.
    1638          $this->coursecat_include_js();
    1639  
    1640          $content = html_writer::start_tag('div', array(
    1641              'class' => join(' ', $classes),
    1642              'data-categoryid' => $coursecat->id,
    1643              'data-depth' => $depth,
    1644              'data-showcourses' => $chelper->get_show_courses(),
    1645              'data-type' => self::COURSECAT_TYPE_CATEGORY,
    1646          ));
    1647  
    1648          // category name
    1649          $categoryname = $coursecat->get_formatted_name();
    1650          $categoryname = html_writer::link(new moodle_url('/course/index.php',
    1651                  array('categoryid' => $coursecat->id)),
    1652                  $categoryname);
    1653          if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
    1654                  && ($coursescount = $coursecat->get_courses_count())) {
    1655              $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
    1656                      array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
    1657          }
    1658          $content .= html_writer::start_tag('div', array('class' => 'info'));
    1659  
    1660          $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname aabtn'));
    1661          $content .= html_writer::end_tag('div'); // .info
    1662  
    1663          // add category content to the output
    1664          $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
    1665  
    1666          $content .= html_writer::end_tag('div'); // .category
    1667  
    1668          // Return the course category tree HTML
    1669          return $content;
    1670      }
    1671  
    1672      /**
    1673       * Returns HTML to display a tree of subcategories and courses in the given category
    1674       *
    1675       * @param coursecat_helper $chelper various display options
    1676       * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
    1677       * @return string
    1678       */
    1679      protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
    1680          // Reset the category expanded flag for this course category tree first.
    1681          $this->categoryexpandedonload = false;
    1682          $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
    1683          if (empty($categorycontent)) {
    1684              return '';
    1685          }
    1686  
    1687          // Start content generation
    1688          $content = '';
    1689          $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
    1690          $content .= html_writer::start_tag('div', $attributes);
    1691  
    1692          if ($coursecat->get_children_count()) {
    1693              $classes = array(
    1694                  'collapseexpand', 'aabtn'
    1695              );
    1696  
    1697              // Check if the category content contains subcategories with children's content loaded.
    1698              if ($this->categoryexpandedonload) {
    1699                  $classes[] = 'collapse-all';
    1700                  $linkname = get_string('collapseall');
    1701              } else {
    1702                  $linkname = get_string('expandall');
    1703              }
    1704  
    1705              // Only show the collapse/expand if there are children to expand.
    1706              $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
    1707              $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
    1708              $content .= html_writer::end_tag('div');
    1709              $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
    1710          }
    1711  
    1712          $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
    1713  
    1714          $content .= html_writer::end_tag('div'); // .course_category_tree
    1715  
    1716          return $content;
    1717      }
    1718  
    1719      /**
    1720       * Renders HTML to display particular course category - list of it's subcategories and courses
    1721       *
    1722       * Invoked from /course/index.php
    1723       *
    1724       * @param int|stdClass|core_course_category $category
    1725       */
    1726      public function course_category($category) {
    1727          global $CFG;
    1728          $usertop = core_course_category::user_top();
    1729          if (empty($category)) {
    1730              $coursecat = $usertop;
    1731          } else if (is_object($category) && $category instanceof core_course_category) {
    1732              $coursecat = $category;
    1733          } else {
    1734              $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
    1735          }
    1736          $site = get_site();
    1737          $output = '';
    1738  
    1739          if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
    1740              // Add 'Manage' button if user has permissions to edit this category.
    1741              $managebutton = $this->single_button(new moodle_url('/course/management.php',
    1742                  array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
    1743              $this->page->set_button($managebutton);
    1744          }
    1745  
    1746          if (core_course_category::is_simple_site()) {
    1747              // There is only one category in the system, do not display link to it.
    1748              $strfulllistofcourses = get_string('fulllistofcourses');
    1749              $this->page->set_title("$site->shortname: $strfulllistofcourses");
    1750          } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
    1751              $strcategories = get_string('categories');
    1752              $this->page->set_title("$site->shortname: $strcategories");
    1753          } else {
    1754              $strfulllistofcourses = get_string('fulllistofcourses');
    1755              $this->page->set_title("$site->shortname: $strfulllistofcourses");
    1756  
    1757              // Print the category selector
    1758              $categorieslist = core_course_category::make_categories_list();
    1759              if (count($categorieslist) > 1) {
    1760                  $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
    1761                  $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
    1762                          core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
    1763                  $select->set_label(get_string('categories').':');
    1764                  $output .= $this->render($select);
    1765                  $output .= html_writer::end_tag('div'); // .categorypicker
    1766              }
    1767          }
    1768  
    1769          // Print current category description
    1770          $chelper = new coursecat_helper();
    1771          if ($description = $chelper->get_category_formatted_description($coursecat)) {
    1772              $output .= $this->box($description, array('class' => 'generalbox info'));
    1773          }
    1774  
    1775          // Prepare parameters for courses and categories lists in the tree
    1776          $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
    1777                  ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
    1778  
    1779          $coursedisplayoptions = array();
    1780          $catdisplayoptions = array();
    1781          $browse = optional_param('browse', null, PARAM_ALPHA);
    1782          $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
    1783          $page = optional_param('page', 0, PARAM_INT);
    1784          $baseurl = new moodle_url('/course/index.php');
    1785          if ($coursecat->id) {
    1786              $baseurl->param('categoryid', $coursecat->id);
    1787          }
    1788          if ($perpage != $CFG->coursesperpage) {
    1789              $baseurl->param('perpage', $perpage);
    1790          }
    1791          $coursedisplayoptions['limit'] = $perpage;
    1792          $catdisplayoptions['limit'] = $perpage;
    1793          if ($browse === 'courses' || !$coursecat->get_children_count()) {
    1794              $coursedisplayoptions['offset'] = $page * $perpage;
    1795              $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
    1796              $catdisplayoptions['nodisplay'] = true;
    1797              $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
    1798              $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
    1799          } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
    1800              $coursedisplayoptions['nodisplay'] = true;
    1801              $catdisplayoptions['offset'] = $page * $perpage;
    1802              $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
    1803              $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
    1804              $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
    1805          } else {
    1806              // we have a category that has both subcategories and courses, display pagination separately
    1807              $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
    1808              $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
    1809          }
    1810          $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
    1811          // Add course search form.
    1812          $output .= $this->course_search_form();
    1813  
    1814          // Display course category tree.
    1815          $output .= $this->coursecat_tree($chelper, $coursecat);
    1816  
    1817          // Add action buttons
    1818          $output .= $this->container_start('buttons');
    1819          if ($coursecat->is_uservisible()) {
    1820              $context = get_category_or_system_context($coursecat->id);
    1821              if (has_capability('moodle/course:create', $context)) {
    1822                  // Print link to create a new course, for the 1st available category.
    1823                  if ($coursecat->id) {
    1824                      $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
    1825                  } else {
    1826                      $url = new moodle_url('/course/edit.php',
    1827                          array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
    1828                  }
    1829                  $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
    1830              }
    1831              ob_start();
    1832              print_course_request_buttons($context);
    1833              $output .= ob_get_contents();
    1834              ob_end_clean();
    1835          }
    1836          $output .= $this->container_end();
    1837  
    1838          return $output;
    1839      }
    1840  
    1841      /**
    1842       * Serves requests to /course/category.ajax.php
    1843       *
    1844       * In this renderer implementation it may expand the category content or
    1845       * course content.
    1846       *
    1847       * @return string
    1848       * @throws coding_exception
    1849       */
    1850      public function coursecat_ajax() {
    1851          global $DB, $CFG;
    1852  
    1853          $type = required_param('type', PARAM_INT);
    1854  
    1855          if ($type === self::COURSECAT_TYPE_CATEGORY) {
    1856              // This is a request for a category list of some kind.
    1857              $categoryid = required_param('categoryid', PARAM_INT);
    1858              $showcourses = required_param('showcourses', PARAM_INT);
    1859              $depth = required_param('depth', PARAM_INT);
    1860  
    1861              $category = core_course_category::get($categoryid);
    1862  
    1863              $chelper = new coursecat_helper();
    1864              $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
    1865              $coursedisplayoptions = array(
    1866                  'limit' => $CFG->coursesperpage,
    1867                  'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
    1868              );
    1869              $catdisplayoptions = array(
    1870                  'limit' => $CFG->coursesperpage,
    1871                  'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
    1872              );
    1873              $chelper->set_show_courses($showcourses)->
    1874                      set_courses_display_options($coursedisplayoptions)->
    1875                      set_categories_display_options($catdisplayoptions);
    1876  
    1877              return $this->coursecat_category_content($chelper, $category, $depth);
    1878          } else if ($type === self::COURSECAT_TYPE_COURSE) {
    1879              // This is a request for the course information.
    1880              $courseid = required_param('courseid', PARAM_INT);
    1881  
    1882              $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
    1883  
    1884              $chelper = new coursecat_helper();
    1885              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
    1886              return $this->coursecat_coursebox_content($chelper, $course);
    1887          } else {
    1888              throw new coding_exception('Invalid request type');
    1889          }
    1890      }
    1891  
    1892      /**
    1893       * Renders html to display search result page
    1894       *
    1895       * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
    1896       * @return string
    1897       */
    1898      public function search_courses($searchcriteria) {
    1899          global $CFG;
    1900          $content = '';
    1901  
    1902          $search = '';
    1903          if (!empty($searchcriteria['search'])) {
    1904              $search = $searchcriteria['search'];
    1905          }
    1906          $content .= $this->course_search_form($search);
    1907  
    1908          if (!empty($searchcriteria)) {
    1909              // print search results
    1910  
    1911              $displayoptions = array('sort' => array('displayname' => 1));
    1912              // take the current page and number of results per page from query
    1913              $perpage = optional_param('perpage', 0, PARAM_RAW);
    1914              if ($perpage !== 'all') {
    1915                  $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
    1916                  $page = optional_param('page', 0, PARAM_INT);
    1917                  $displayoptions['offset'] = $displayoptions['limit'] * $page;
    1918              }
    1919              // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
    1920              $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
    1921              $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
    1922  
    1923              $class = 'course-search-result';
    1924              foreach ($searchcriteria as $key => $value) {
    1925                  if (!empty($value)) {
    1926                      $class .= ' course-search-result-'. $key;
    1927                  }
    1928              }
    1929              $chelper = new coursecat_helper();
    1930              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
    1931                      set_courses_display_options($displayoptions)->
    1932                      set_search_criteria($searchcriteria)->
    1933                      set_attributes(array('class' => $class));
    1934  
    1935              $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
    1936              $totalcount = core_course_category::search_courses_count($searchcriteria);
    1937              $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
    1938  
    1939              if (!$totalcount) {
    1940                  if (!empty($searchcriteria['search'])) {
    1941                      $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
    1942                  } else {
    1943                      $content .= $this->heading(get_string('novalidcourses'));
    1944                  }
    1945              } else {
    1946                  $content .= $this->heading(get_string('searchresults'). ": $totalcount");
    1947                  $content .= $courseslist;
    1948              }
    1949          }
    1950          return $content;
    1951      }
    1952  
    1953      /**
    1954       * Renders html to print list of courses tagged with particular tag
    1955       *
    1956       * @param int $tagid id of the tag
    1957       * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
    1958       *             are displayed on the page and the per-page limit may be bigger
    1959       * @param int $fromctx context id where the link was displayed, may be used by callbacks
    1960       *            to display items in the same context first
    1961       * @param int $ctx context id where to search for records
    1962       * @param bool $rec search in subcontexts as well
    1963       * @param array $displayoptions
    1964       * @return string empty string if no courses are marked with this tag or rendered list of courses
    1965       */
    1966      public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
    1967          global $CFG;
    1968          if (empty($displayoptions)) {
    1969              $displayoptions = array();
    1970          }
    1971          $showcategories = !core_course_category::is_simple_site();
    1972          $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
    1973          $chelper = new coursecat_helper();
    1974          $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
    1975          $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
    1976                      self::COURSECAT_SHOW_COURSES_EXPANDED)->
    1977                  set_search_criteria($searchcriteria)->
    1978                  set_courses_display_options($displayoptions)->
    1979                  set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
    1980                  // (we set the same css class as in search results by tagid)
    1981          if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
    1982              $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
    1983              if ($exclusivemode) {
    1984                  return $this->coursecat_courses($chelper, $courses, $totalcount);
    1985              } else {
    1986                  $tagfeed = new core_tag\output\tagfeed();
    1987                  $img = $this->output->pix_icon('i/course', '');
    1988                  foreach ($courses as $course) {
    1989                      $url = course_get_url($course);
    1990                      $imgwithlink = html_writer::link($url, $img);
    1991                      $coursename = html_writer::link($url, $course->get_formatted_name());
    1992                      $details = '';
    1993                      if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
    1994                          $details = get_string('category').': '.
    1995                                  html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
    1996                                          $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
    1997                      }
    1998                      $tagfeed->add($imgwithlink, $coursename, $details);
    1999                  }
    2000                  return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
    2001              }
    2002          }
    2003          return '';
    2004      }
    2005  
    2006      /**
    2007       * Returns HTML to display one remote course
    2008       *
    2009       * @param stdClass $course remote course information, contains properties:
    2010             id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
    2011       * @return string
    2012       */
    2013      protected function frontpage_remote_course(stdClass $course) {
    2014          $url = new moodle_url('/auth/mnet/jump.php', array(
    2015              'hostid' => $course->hostid,
    2016              'wantsurl' => '/course/view.php?id='. $course->remoteid
    2017          ));
    2018  
    2019          $output = '';
    2020          $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
    2021          $output .= html_writer::start_tag('div', array('class' => 'info'));
    2022          $output .= html_writer::start_tag('h3', array('class' => 'name'));
    2023          $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
    2024          $output .= html_writer::end_tag('h3'); // .name
    2025          $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
    2026          $output .= html_writer::end_tag('div'); // .info
    2027          $output .= html_writer::start_tag('div', array('class' => 'content'));
    2028          $output .= html_writer::start_tag('div', array('class' => 'summary'));
    2029          $options = new stdClass();
    2030          $options->noclean = true;
    2031          $options->para = false;
    2032          $options->overflowdiv = true;
    2033          $output .= format_text($course->summary, $course->summaryformat, $options);
    2034          $output .= html_writer::end_tag('div'); // .summary
    2035          $addinfo = format_string($course->hostname) . ' : '
    2036              . format_string($course->cat_name) . ' : '
    2037              . format_string($course->shortname);
    2038          $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
    2039          $output .= html_writer::end_tag('div'); // .content
    2040          $output .= html_writer::end_tag('div'); // .coursebox
    2041          return $output;
    2042      }
    2043  
    2044      /**
    2045       * Returns HTML to display one remote host
    2046       *
    2047       * @param array $host host information, contains properties: name, url, count
    2048       * @return string
    2049       */
    2050      protected function frontpage_remote_host($host) {
    2051          $output = '';
    2052          $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
    2053          $output .= html_writer::start_tag('div', array('class' => 'info'));
    2054          $output .= html_writer::start_tag('h3', array('class' => 'name'));
    2055          $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
    2056          $output .= html_writer::end_tag('h3'); // .name
    2057          $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
    2058          $output .= html_writer::end_tag('div'); // .info
    2059          $output .= html_writer::start_tag('div', array('class' => 'content'));
    2060          $output .= html_writer::start_tag('div', array('class' => 'summary'));
    2061          $output .= $host['count'] . ' ' . get_string('courses');
    2062          $output .= html_writer::end_tag('div'); // .content
    2063          $output .= html_writer::end_tag('div'); // .coursebox
    2064          return $output;
    2065      }
    2066  
    2067      /**
    2068       * Returns HTML to print list of courses user is enrolled to for the frontpage
    2069       *
    2070       * Also lists remote courses or remote hosts if MNET authorisation is used
    2071       *
    2072       * @return string
    2073       */
    2074      public function frontpage_my_courses() {
    2075          global $USER, $CFG, $DB;
    2076  
    2077          if (!isloggedin() or isguestuser()) {
    2078              return '';
    2079          }
    2080  
    2081          $output = '';
    2082          $courses  = enrol_get_my_courses('summary, summaryformat');
    2083          $rhosts   = array();
    2084          $rcourses = array();
    2085          if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
    2086              $rcourses = get_my_remotecourses($USER->id);
    2087              $rhosts   = get_my_remotehosts();
    2088          }
    2089  
    2090          if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
    2091  
    2092              $chelper = new coursecat_helper();
    2093              $totalcount = count($courses);
    2094              if (count($courses) > $CFG->frontpagecourselimit) {
    2095                  // There are more enrolled courses than we can display, display link to 'My courses'.
    2096                  $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
    2097                  $chelper->set_courses_display_options(array(
    2098                          'viewmoreurl' => new moodle_url('/my/'),
    2099                          'viewmoretext' => new lang_string('mycourses')
    2100                      ));
    2101              } else if (core_course_category::top()->is_uservisible()) {
    2102                  // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
    2103                  $chelper->set_courses_display_options(array(
    2104                          'viewmoreurl' => new moodle_url('/course/index.php'),
    2105                          'viewmoretext' => new lang_string('fulllistofcourses')
    2106                      ));
    2107                  $totalcount = $DB->count_records('course') - 1;
    2108              }
    2109              $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
    2110                      set_attributes(array('class' => 'frontpage-course-list-enrolled'));
    2111              $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
    2112  
    2113              // MNET
    2114              if (!empty($rcourses)) {
    2115                  // at the IDP, we know of all the remote courses
    2116                  $output .= html_writer::start_tag('div', array('class' => 'courses'));
    2117                  foreach ($rcourses as $course) {
    2118                      $output .= $this->frontpage_remote_course($course);
    2119                  }
    2120                  $output .= html_writer::end_tag('div'); // .courses
    2121              } elseif (!empty($rhosts)) {
    2122                  // non-IDP, we know of all the remote servers, but not courses
    2123                  $output .= html_writer::start_tag('div', array('class' => 'courses'));
    2124                  foreach ($rhosts as $host) {
    2125                      $output .= $this->frontpage_remote_host($host);
    2126                  }
    2127                  $output .= html_writer::end_tag('div'); // .courses
    2128              }
    2129          }
    2130          return $output;
    2131      }
    2132  
    2133      /**
    2134       * Returns HTML to print list of available courses for the frontpage
    2135       *
    2136       * @return string
    2137       */
    2138      public function frontpage_available_courses() {
    2139          global $CFG;
    2140  
    2141          $chelper = new coursecat_helper();
    2142          $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
    2143                  set_courses_display_options(array(
    2144                      'recursive' => true,
    2145                      'limit' => $CFG->frontpagecourselimit,
    2146                      'viewmoreurl' => new moodle_url('/course/index.php'),
    2147                      'viewmoretext' => new lang_string('fulllistofcourses')));
    2148  
    2149          $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
    2150          $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
    2151          $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
    2152          if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
    2153              // Print link to create a new course, for the 1st available category.
    2154              return $this->add_new_course_button();
    2155          }
    2156          return $this->coursecat_courses($chelper, $courses, $totalcount);
    2157      }
    2158  
    2159      /**
    2160       * Returns HTML to the "add new course" button for the page
    2161       *
    2162       * @return string
    2163       */
    2164      public function add_new_course_button() {
    2165          global $CFG;
    2166          // Print link to create a new course, for the 1st available category.
    2167          $output = $this->container_start('buttons');
    2168          $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
    2169          $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
    2170          $output .= $this->container_end('buttons');
    2171          return $output;
    2172      }
    2173  
    2174      /**
    2175       * Returns HTML to print tree with course categories and courses for the frontpage
    2176       *
    2177       * @return string
    2178       */
    2179      public function frontpage_combo_list() {
    2180          global $CFG;
    2181          // TODO MDL-10965 improve.
    2182          $tree = core_course_category::top();
    2183          if (!$tree->get_children_count()) {
    2184              return '';
    2185          }
    2186          $chelper = new coursecat_helper();
    2187          $chelper->set_subcat_depth($CFG->maxcategorydepth)->
    2188              set_categories_display_options(array(
    2189                  'limit' => $CFG->coursesperpage,
    2190                  'viewmoreurl' => new moodle_url('/course/index.php',
    2191                          array('browse' => 'categories', 'page' => 1))
    2192              ))->
    2193              set_courses_display_options(array(
    2194                  'limit' => $CFG->coursesperpage,
    2195                  'viewmoreurl' => new moodle_url('/course/index.php',
    2196                          array('browse' => 'courses', 'page' => 1))
    2197              ))->
    2198              set_attributes(array('class' => 'frontpage-category-combo'));
    2199          return $this->coursecat_tree($chelper, $tree);
    2200      }
    2201  
    2202      /**
    2203       * Returns HTML to print tree of course categories (with number of courses) for the frontpage
    2204       *
    2205       * @return string
    2206       */
    2207      public function frontpage_categories_list() {
    2208          global $CFG;
    2209          // TODO MDL-10965 improve.
    2210          $tree = core_course_category::top();
    2211          if (!$tree->get_children_count()) {
    2212              return '';
    2213          }
    2214          $chelper = new coursecat_helper();
    2215          $chelper->set_subcat_depth($CFG->maxcategorydepth)->
    2216                  set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
    2217                  set_categories_display_options(array(
    2218                      'limit' => $CFG->coursesperpage,
    2219                      'viewmoreurl' => new moodle_url('/course/index.php',
    2220                              array('browse' => 'categories', 'page' => 1))
    2221                  ))->
    2222                  set_attributes(array('class' => 'frontpage-category-names'));
    2223          return $this->coursecat_tree($chelper, $tree);
    2224      }
    2225  
    2226      /**
    2227       * Renders the activity information.
    2228       *
    2229       * Defer to template.
    2230       *
    2231       * @param \core_course\output\activity_information $page
    2232       * @return string html for the page
    2233       */
    2234      public function render_activity_information(\core_course\output\activity_information $page) {
    2235          $data = $page->export_for_template($this->output);
    2236          return $this->output->render_from_template('core_course/activity_info', $data);
    2237      }
    2238  
    2239      /**
    2240       * Renders the activity navigation.
    2241       *
    2242       * Defer to template.
    2243       *
    2244       * @param \core_course\output\activity_navigation $page
    2245       * @return string html for the page
    2246       */
    2247      public function render_activity_navigation(\core_course\output\activity_navigation $page) {
    2248          $data = $page->export_for_template($this->output);
    2249          return $this->output->render_from_template('core_course/activity_navigation', $data);
    2250      }
    2251  
    2252      /**
    2253       * Display waiting information about backup size during uploading backup process
    2254       * @param object $backupfile the backup stored_file
    2255       * @return $html string
    2256       */
    2257      public function sendingbackupinfo($backupfile) {
    2258          $sizeinfo = new stdClass();
    2259          $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
    2260          $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
    2261              array('class' => 'courseuploadtextinfo'));
    2262          return $html;
    2263      }
    2264  
    2265      /**
    2266       * Hub information (logo - name - description - link)
    2267       * @param object $hubinfo
    2268       * @return string html code
    2269       */
    2270      public function hubinfo($hubinfo) {
    2271          $screenshothtml = html_writer::empty_tag('img',
    2272              array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
    2273          $hubdescription = html_writer::tag('div', $screenshothtml,
    2274              array('class' => 'hubscreenshot'));
    2275  
    2276          $hubdescription .= html_writer::tag('a', $hubinfo['name'],
    2277              array('class' => 'hublink', 'href' => $hubinfo['url'],
    2278                  'onclick' => 'this.target="_blank"'));
    2279  
    2280          $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
    2281              array('class' => 'hubdescription'));
    2282          $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
    2283  
    2284          return $hubdescription;
    2285      }
    2286  
    2287      /**
    2288       * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
    2289       *
    2290       * This may be disabled in settings
    2291       *
    2292       * @return string
    2293       */
    2294      public function frontpage_section1() {
    2295          global $SITE, $USER;
    2296  
    2297          $output = '';
    2298          $editing = $this->page->user_is_editing();
    2299  
    2300          if ($editing) {
    2301              // Make sure section with number 1 exists.
    2302              course_create_sections_if_missing($SITE, 1);
    2303          }
    2304  
    2305          $modinfo = get_fast_modinfo($SITE);
    2306          $section = $modinfo->get_section_info(1);
    2307          if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
    2308              $output .= $this->box_start('generalbox sitetopic');
    2309  
    2310              // If currently moving a file then show the current clipboard.
    2311              if (ismoving($SITE->id)) {
    2312                  $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
    2313                  $output .= '<p><font size="2">';
    2314                  $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
    2315                  $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
    2316                  $output .= '</font></p>';
    2317              }
    2318  
    2319              $context = context_course::instance(SITEID);
    2320  
    2321              // If the section name is set we show it.
    2322              if (trim($section->name) !== '') {
    2323                  $output .= $this->heading(
    2324                      format_string($section->name, true, array('context' => $context)),
    2325                      2,
    2326                      'sectionname'
    2327                  );
    2328              }
    2329  
    2330              $summarytext = file_rewrite_pluginfile_urls($section->summary,
    2331                  'pluginfile.php',
    2332                  $context->id,
    2333                  'course',
    2334                  'section',
    2335                  $section->id);
    2336              $summaryformatoptions = new stdClass();
    2337              $summaryformatoptions->noclean = true;
    2338              $summaryformatoptions->overflowdiv = true;
    2339  
    2340              $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
    2341  
    2342              if ($editing && has_capability('moodle/course:update', $context)) {
    2343                  $streditsummary = get_string('editsummary');
    2344                  $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
    2345                  $attributes = ['title' => $streditsummary, 'aria-label' => $streditsummary];
    2346                  $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', ''), $attributes) .
    2347                      "<br /><br />";
    2348              }
    2349  
    2350              $output .= $this->course_section_cm_list($SITE, $section);
    2351  
    2352              $output .= $this->course_section_add_cm_control($SITE, $section->section);
    2353              $output .= $this->box_end();
    2354          }
    2355  
    2356          return $output;
    2357      }
    2358  
    2359      /**
    2360       * Output news for the frontpage (extract from site-wide news forum)
    2361       *
    2362       * @param stdClass $forum record from db table 'forum' that represents the site news forum
    2363       * @return string
    2364       */
    2365      protected function frontpage_news($forum) {
    2366          global $CFG, $SITE, $SESSION, $USER;
    2367          require_once($CFG->dirroot .'/mod/forum/lib.php');
    2368  
    2369          $output = '';
    2370  
    2371          if (isloggedin()) {
    2372              $SESSION->fromdiscussion = $CFG->wwwroot;
    2373              $subtext = '';
    2374              if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
    2375                  if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
    2376                      $subtext = get_string('unsubscribe', 'forum');
    2377                  }
    2378              } else {
    2379                  $subtext = get_string('subscribe', 'forum');
    2380              }
    2381              $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
    2382              $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
    2383          }
    2384  
    2385          $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
    2386          $context = context_module::instance($coursemodule->id);
    2387  
    2388          $entityfactory = mod_forum\local\container::get_entity_factory();
    2389          $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
    2390  
    2391          $rendererfactory = mod_forum\local\container::get_renderer_factory();
    2392          $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
    2393          $cm = \cm_info::create($coursemodule);
    2394          return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
    2395      }
    2396  
    2397      /**
    2398       * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
    2399       *
    2400       * @param string $skipdivid
    2401       * @param string $contentsdivid
    2402       * @param string $header Header of the part
    2403       * @param string $contents Contents of the part
    2404       * @return string
    2405       */
    2406      protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
    2407          if (strval($contents) === '') {
    2408              return '';
    2409          }
    2410          $output = html_writer::link('#' . $skipdivid,
    2411              get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
    2412              array('class' => 'skip-block skip aabtn'));
    2413  
    2414          // Wrap frontpage part in div container.
    2415          $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
    2416          $output .= $this->heading($header);
    2417  
    2418          $output .= $contents;
    2419  
    2420          // End frontpage part div container.
    2421          $output .= html_writer::end_tag('div');
    2422  
    2423          $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
    2424          return $output;
    2425      }
    2426  
    2427      /**
    2428       * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
    2429       *
    2430       * @return string
    2431       */
    2432      public function frontpage() {
    2433          global $CFG, $SITE;
    2434  
    2435          $output = '';
    2436  
    2437          if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
    2438              $frontpagelayout = $CFG->frontpageloggedin;
    2439          } else {
    2440              $frontpagelayout = $CFG->frontpage;
    2441          }
    2442  
    2443          foreach (explode(',', $frontpagelayout) as $v) {
    2444              switch ($v) {
    2445                  // Display the main part of the front page.
    2446                  case FRONTPAGENEWS:
    2447                      if ($SITE->newsitems) {
    2448                          // Print forums only when needed.
    2449                          require_once($CFG->dirroot .'/mod/forum/lib.php');
    2450                          if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
    2451                                  ($forumcontents = $this->frontpage_news($newsforum))) {
    2452                              $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
    2453                              $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
    2454                                  $newsforumcm->get_formatted_name(), $forumcontents);
    2455                          }
    2456                      }
    2457                      break;
    2458  
    2459                  case FRONTPAGEENROLLEDCOURSELIST:
    2460                      $mycourseshtml = $this->frontpage_my_courses();
    2461                      if (!empty($mycourseshtml)) {
    2462                          $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
    2463                              get_string('mycourses'), $mycourseshtml);
    2464                      }
    2465                      break;
    2466  
    2467                  case FRONTPAGEALLCOURSELIST:
    2468                      $availablecourseshtml = $this->frontpage_available_courses();
    2469                      $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
    2470                          get_string('availablecourses'), $availablecourseshtml);
    2471                      break;
    2472  
    2473                  case FRONTPAGECATEGORYNAMES:
    2474                      $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
    2475                          get_string('categories'), $this->frontpage_categories_list());
    2476                      break;
    2477  
    2478                  case FRONTPAGECATEGORYCOMBO:
    2479                      $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
    2480                          get_string('courses'), $this->frontpage_combo_list());
    2481                      break;
    2482  
    2483                  case FRONTPAGECOURSESEARCH:
    2484                      $output .= $this->box($this->course_search_form(''), 'd-flex justify-content-center');
    2485                      break;
    2486  
    2487              }
    2488              $output .= '<br />';
    2489          }
    2490  
    2491          return $output;
    2492      }
    2493  }
    2494  
    2495  /**
    2496   * Class storing display options and functions to help display course category and/or courses lists
    2497   *
    2498   * This is a wrapper for core_course_category objects that also stores display options
    2499   * and functions to retrieve sorted and paginated lists of categories/courses.
    2500   *
    2501   * If theme overrides methods in core_course_renderers that access this class
    2502   * it may as well not use this class at all or extend it.
    2503   *
    2504   * @package   core
    2505   * @copyright 2013 Marina Glancy
    2506   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2507   */
    2508  class coursecat_helper {
    2509      /** @var string [none, collapsed, expanded] how (if) display courses list */
    2510      protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
    2511      /** @var int depth to expand subcategories in the tree (deeper subcategories will be loaded by AJAX or proceed to category page by clicking on category name) */
    2512      protected $subcatdepth = 1;
    2513      /** @var array options to display courses list */
    2514      protected $coursesdisplayoptions = array();
    2515      /** @var array options to display subcategories list */
    2516      protected $categoriesdisplayoptions = array();
    2517      /** @var array additional HTML attributes */
    2518      protected $attributes = array();
    2519      /** @var array search criteria if the list is a search result */
    2520      protected $searchcriteria = null;
    2521  
    2522      /**
    2523       * Sets how (if) to show the courses - none, collapsed, expanded, etc.
    2524       *
    2525       * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
    2526       * @return coursecat_helper
    2527       */
    2528      public function set_show_courses($showcourses) {
    2529          $this->showcourses = $showcourses;
    2530          // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
    2531          // and core_course_category::search_courses().
    2532          $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
    2533          $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
    2534          $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
    2535          return $this;
    2536      }
    2537  
    2538      /**
    2539       * Returns how (if) to show the courses - none, collapsed, expanded, etc.
    2540       *
    2541       * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
    2542       */
    2543      public function get_show_courses() {
    2544          return $this->showcourses;
    2545      }
    2546  
    2547      /**
    2548       * Sets the maximum depth to expand subcategories in the tree
    2549       *
    2550       * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
    2551       *
    2552       * @param int $subcatdepth
    2553       * @return coursecat_helper
    2554       */
    2555      public function set_subcat_depth($subcatdepth) {
    2556          $this->subcatdepth = $subcatdepth;
    2557          return $this;
    2558      }
    2559  
    2560      /**
    2561       * Returns the maximum depth to expand subcategories in the tree
    2562       *
    2563       * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
    2564       *
    2565       * @return int
    2566       */
    2567      public function get_subcat_depth() {
    2568          return $this->subcatdepth;
    2569      }
    2570  
    2571      /**
    2572       * Sets options to display list of courses
    2573       *
    2574       * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
    2575       *
    2576       * Options that core_course_category::get_courses() accept:
    2577       *    - recursive - return courses from subcategories as well. Use with care,
    2578       *      this may be a huge list!
    2579       *    - summary - preloads fields 'summary' and 'summaryformat'
    2580       *    - coursecontacts - preloads course contacts
    2581       *    - customfields - preloads custom fields data
    2582       *    - isenrolled - preloads indication whether this user is enrolled in the course
    2583       *    - sort - list of fields to sort. Example
    2584       *             array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
    2585       *             will sort by idnumber asc, shortname asc and id desc.
    2586       *             Default: array('sortorder' => 1)
    2587       *             Only cached fields may be used for sorting!
    2588       *    - offset
    2589       *    - limit - maximum number of children to return, 0 or null for no limit
    2590       *
    2591       * Options summary and coursecontacts are filled automatically in the set_show_courses()
    2592       *
    2593       * Also renderer can set here any additional options it wants to pass between renderer functions.
    2594       *
    2595       * @param array $options
    2596       * @return coursecat_helper
    2597       */
    2598      public function set_courses_display_options($options) {
    2599          $this->coursesdisplayoptions = $options;
    2600          $this->set_show_courses($this->showcourses); // this will calculate special display options
    2601          return $this;
    2602      }
    2603  
    2604      /**
    2605       * Sets one option to display list of courses
    2606       *
    2607       * @see coursecat_helper::set_courses_display_options()
    2608       *
    2609       * @param string $key
    2610       * @param mixed $value
    2611       * @return coursecat_helper
    2612       */
    2613      public function set_courses_display_option($key, $value) {
    2614          $this->coursesdisplayoptions[$key] = $value;
    2615          return $this;
    2616      }
    2617  
    2618      /**
    2619       * Return the specified option to display list of courses
    2620       *
    2621       * @param string $optionname option name
    2622       * @param mixed $defaultvalue default value for option if it is not specified
    2623       * @return mixed
    2624       */
    2625      public function get_courses_display_option($optionname, $defaultvalue = null) {
    2626          if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
    2627              return $this->coursesdisplayoptions[$optionname];
    2628          } else {
    2629              return $defaultvalue;
    2630          }
    2631      }
    2632  
    2633      /**
    2634       * Returns all options to display the courses
    2635       *
    2636       * This array is usually passed to {@link core_course_category::get_courses()} or
    2637       * {@link core_course_category::search_courses()}
    2638       *
    2639       * @return array
    2640       */
    2641      public function get_courses_display_options() {
    2642          return $this->coursesdisplayoptions;
    2643      }
    2644  
    2645      /**
    2646       * Sets options to display list of subcategories
    2647       *
    2648       * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
    2649       * Any other options may be used by renderer functions
    2650       *
    2651       * @param array $options
    2652       * @return coursecat_helper
    2653       */
    2654      public function set_categories_display_options($options) {
    2655          $this->categoriesdisplayoptions = $options;
    2656          return $this;
    2657      }
    2658  
    2659      /**
    2660       * Return the specified option to display list of subcategories
    2661       *
    2662       * @param string $optionname option name
    2663       * @param mixed $defaultvalue default value for option if it is not specified
    2664       * @return mixed
    2665       */
    2666      public function get_categories_display_option($optionname, $defaultvalue = null) {
    2667          if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
    2668              return $this->categoriesdisplayoptions[$optionname];
    2669          } else {
    2670              return $defaultvalue;
    2671          }
    2672      }
    2673  
    2674      /**
    2675       * Returns all options to display list of subcategories
    2676       *
    2677       * This array is usually passed to {@link core_course_category::get_children()}
    2678       *
    2679       * @return array
    2680       */
    2681      public function get_categories_display_options() {
    2682          return $this->categoriesdisplayoptions;
    2683      }
    2684  
    2685      /**
    2686       * Sets additional general options to pass between renderer functions, usually HTML attributes
    2687       *
    2688       * @param array $attributes
    2689       * @return coursecat_helper
    2690       */
    2691      public function set_attributes($attributes) {
    2692          $this->attributes = $attributes;
    2693          return $this;
    2694      }
    2695  
    2696      /**
    2697       * Return all attributes and erases them so they are not applied again
    2698       *
    2699       * @param string $classname adds additional class name to the beginning of $attributes['class']
    2700       * @return array
    2701       */
    2702      public function get_and_erase_attributes($classname) {
    2703          $attributes = $this->attributes;
    2704          $this->attributes = array();
    2705          if (empty($attributes['class'])) {
    2706              $attributes['class'] = '';
    2707          }
    2708          $attributes['class'] = $classname . ' '. $attributes['class'];
    2709          return $attributes;
    2710      }
    2711  
    2712      /**
    2713       * Sets the search criteria if the course is a search result
    2714       *
    2715       * Search string will be used to highlight terms in course name and description
    2716       *
    2717       * @param array $searchcriteria
    2718       * @return coursecat_helper
    2719       */
    2720      public function set_search_criteria($searchcriteria) {
    2721          $this->searchcriteria = $searchcriteria;
    2722          return $this;
    2723      }
    2724  
    2725      /**
    2726       * Returns formatted and filtered description of the given category
    2727       *
    2728       * @param core_course_category $coursecat category
    2729       * @param stdClass|array $options format options, by default [noclean,overflowdiv],
    2730       *     if context is not specified it will be added automatically
    2731       * @return string|null
    2732       */
    2733      public function get_category_formatted_description($coursecat, $options = null) {
    2734          if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
    2735              if (!isset($coursecat->descriptionformat)) {
    2736                  $descriptionformat = FORMAT_MOODLE;
    2737              } else {
    2738                  $descriptionformat = $coursecat->descriptionformat;
    2739              }
    2740              if ($options === null) {
    2741                  $options = array('noclean' => true, 'overflowdiv' => true);
    2742              } else {
    2743                  $options = (array)$options;
    2744              }
    2745              $context = context_coursecat::instance($coursecat->id);
    2746              if (!isset($options['context'])) {
    2747                  $options['context'] = $context;
    2748              }
    2749              $text = file_rewrite_pluginfile_urls($coursecat->description,
    2750                      'pluginfile.php', $context->id, 'coursecat', 'description', null);
    2751              return format_text($text, $descriptionformat, $options);
    2752          }
    2753          return null;
    2754      }
    2755  
    2756      /**
    2757       * Returns given course's summary with proper embedded files urls and formatted
    2758       *
    2759       * @param core_course_list_element $course
    2760       * @param array|stdClass $options additional formatting options
    2761       * @return string
    2762       */
    2763      public function get_course_formatted_summary($course, $options = array()) {
    2764          global $CFG;
    2765          require_once($CFG->libdir. '/filelib.php');
    2766          if (!$course->has_summary()) {
    2767              return '';
    2768          }
    2769          $options = (array)$options;
    2770          $context = context_course::instance($course->id);
    2771          if (!isset($options['context'])) {
    2772              // TODO see MDL-38521
    2773              // option 1 (current), page context - no code required
    2774              // option 2, system context
    2775              // $options['context'] = context_system::instance();
    2776              // option 3, course context:
    2777              // $options['context'] = $context;
    2778              // option 4, course category context:
    2779              // $options['context'] = $context->get_parent_context();
    2780          }
    2781          $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
    2782          $summary = format_text($summary, $course->summaryformat, $options, $course->id);
    2783          if (!empty($this->searchcriteria['search'])) {
    2784              $summary = highlight($this->searchcriteria['search'], $summary);
    2785          }
    2786          return $summary;
    2787      }
    2788  
    2789      /**
    2790       * Returns course name as it is configured to appear in courses lists formatted to course context
    2791       *
    2792       * @param core_course_list_element $course
    2793       * @param array|stdClass $options additional formatting options
    2794       * @return string
    2795       */
    2796      public function get_course_formatted_name($course, $options = array()) {
    2797          $options = (array)$options;
    2798          if (!isset($options['context'])) {
    2799              $options['context'] = context_course::instance($course->id);
    2800          }
    2801          $name = format_string(get_course_display_name_for_list($course), true, $options);
    2802          if (!empty($this->searchcriteria['search'])) {
    2803              $name = highlight($this->searchcriteria['search'], $name);
    2804          }
    2805          return $name;
    2806      }
    2807  }