Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
/mod/label/ -> lib.php (source)

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

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Library of functions and constants for module label
  20   *
  21   * @package mod_label
  22   * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die;
  27  
  28  /** LABEL_MAX_NAME_LENGTH = 50 */
  29  define("LABEL_MAX_NAME_LENGTH", 50);
  30  
  31  /**
  32   * @uses LABEL_MAX_NAME_LENGTH
  33   * @param object $label
  34   * @return string
  35   */
  36  function get_label_name($label) {
  37      $context = context_module::instance($label->coursemodule);
  38      $intro = format_text($label->intro, $label->introformat, ['filter' => false, 'context' => $context]);
  39      $name = html_to_text(format_string($intro, true, ['context' => $context]));
  40      $name = preg_replace('/@@PLUGINFILE@@\/[[:^space:]]+/i', '', $name);
  41      // Remove double space and also nbsp; characters.
  42      $name = preg_replace('/\s+/u', ' ', $name);
  43      $name = trim($name);
  44      if (core_text::strlen($name) > LABEL_MAX_NAME_LENGTH) {
  45          $name = core_text::substr($name, 0, LABEL_MAX_NAME_LENGTH) . "...";
  46      }
  47  
  48      if (empty($name)) {
  49          // arbitrary name
  50          $name = get_string('modulename','label');
  51      }
  52  
  53      return $name;
  54  }
  55  /**
  56   * Given an object containing all the necessary data,
  57   * (defined by the form in mod_form.php) this function
  58   * will create a new instance and return the id number
  59   * of the new instance.
  60   *
  61   * @global object
  62   * @param object $label
  63   * @return bool|int
  64   */
  65  function label_add_instance($label) {
  66      global $DB;
  67  
  68      $label->name = get_label_name($label);
  69      $label->timemodified = time();
  70  
  71      $id = $DB->insert_record("label", $label);
  72  
  73      $completiontimeexpected = !empty($label->completionexpected) ? $label->completionexpected : null;
  74      \core_completion\api::update_completion_date_event($label->coursemodule, 'label', $id, $completiontimeexpected);
  75  
  76      return $id;
  77  }
  78  
  79  /**
  80   * Sets the special label display on course page.
  81   *
  82   * @param cm_info $cm Course-module object
  83   */
  84  function label_cm_info_view(cm_info $cm) {
  85      $cm->set_custom_cmlist_item(true);
  86  }
  87  
  88  /**
  89   * Given an object containing all the necessary data,
  90   * (defined by the form in mod_form.php) this function
  91   * will update an existing instance with new data.
  92   *
  93   * @global object
  94   * @param object $label
  95   * @return bool
  96   */
  97  function label_update_instance($label) {
  98      global $DB;
  99  
 100      $label->name = get_label_name($label);
 101      $label->timemodified = time();
 102      $label->id = $label->instance;
 103  
 104      $completiontimeexpected = !empty($label->completionexpected) ? $label->completionexpected : null;
 105      \core_completion\api::update_completion_date_event($label->coursemodule, 'label', $label->id, $completiontimeexpected);
 106  
 107      return $DB->update_record("label", $label);
 108  }
 109  
 110  /**
 111   * Given an ID of an instance of this module,
 112   * this function will permanently delete the instance
 113   * and any data that depends on it.
 114   *
 115   * @global object
 116   * @param int $id
 117   * @return bool
 118   */
 119  function label_delete_instance($id) {
 120      global $DB;
 121  
 122      if (! $label = $DB->get_record("label", array("id"=>$id))) {
 123          return false;
 124      }
 125  
 126      $result = true;
 127  
 128      $cm = get_coursemodule_from_instance('label', $id);
 129      \core_completion\api::update_completion_date_event($cm->id, 'label', $label->id, null);
 130  
 131      if (! $DB->delete_records("label", array("id"=>$label->id))) {
 132          $result = false;
 133      }
 134  
 135      return $result;
 136  }
 137  
 138  /**
 139   * Given a course_module object, this function returns any
 140   * "extra" information that may be needed when printing
 141   * this activity in a course listing.
 142   * See get_array_of_activities() in course/lib.php
 143   *
 144   * @global object
 145   * @param object $coursemodule
 146   * @return cached_cm_info|null
 147   */
 148  function label_get_coursemodule_info($coursemodule) {
 149      global $DB;
 150  
 151      if ($label = $DB->get_record('label', array('id'=>$coursemodule->instance), 'id, name, intro, introformat')) {
 152          if (empty($label->name)) {
 153              // label name missing, fix it
 154              $label->name = "label{$label->id}";
 155              $DB->set_field('label', 'name', $label->name, array('id'=>$label->id));
 156          }
 157          $info = new cached_cm_info();
 158          // no filtering hre because this info is cached and filtered later
 159          $info->content = format_module_intro('label', $label, $coursemodule->id, false);
 160          $info->name  = $label->name;
 161          return $info;
 162      } else {
 163          return null;
 164      }
 165  }
 166  
 167  /**
 168   * This function is used by the reset_course_userdata function in moodlelib.
 169   *
 170   * @param object $data the data submitted from the reset course.
 171   * @return array status array
 172   */
 173  function label_reset_userdata($data) {
 174  
 175      // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
 176      // See MDL-9367.
 177  
 178      return array();
 179  }
 180  
 181  /**
 182   * @uses FEATURE_IDNUMBER
 183   * @uses FEATURE_GROUPS
 184   * @uses FEATURE_GROUPINGS
 185   * @uses FEATURE_MOD_INTRO
 186   * @uses FEATURE_COMPLETION_TRACKS_VIEWS
 187   * @uses FEATURE_GRADE_HAS_GRADE
 188   * @uses FEATURE_GRADE_OUTCOMES
 189   * @param string $feature FEATURE_xx constant for requested feature
 190   * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
 191   */
 192  function label_supports($feature) {
 193      switch($feature) {
 194          case FEATURE_IDNUMBER:                return true;
 195          case FEATURE_GROUPS:                  return false;
 196          case FEATURE_GROUPINGS:               return false;
 197          case FEATURE_MOD_INTRO:               return true;
 198          case FEATURE_COMPLETION_TRACKS_VIEWS: return false;
 199          case FEATURE_GRADE_HAS_GRADE:         return false;
 200          case FEATURE_GRADE_OUTCOMES:          return false;
 201          case FEATURE_MOD_ARCHETYPE:           return MOD_ARCHETYPE_RESOURCE;
 202          case FEATURE_BACKUP_MOODLE2:          return true;
 203          case FEATURE_NO_VIEW_LINK:            return true;
 204          case FEATURE_MOD_PURPOSE:             return MOD_PURPOSE_CONTENT;
 205  
 206          default: return null;
 207      }
 208  }
 209  
 210  /**
 211   * Register the ability to handle drag and drop file uploads
 212   * @return array containing details of the files / types the mod can handle
 213   */
 214  function label_dndupload_register() {
 215      $strdnd = get_string('dnduploadlabel', 'mod_label');
 216      if (get_config('label', 'dndmedia')) {
 217          $mediaextensions = file_get_typegroup('extension', ['web_image', 'web_video', 'web_audio']);
 218          $files = array();
 219          foreach ($mediaextensions as $extn) {
 220              $extn = trim($extn, '.');
 221              $files[] = array('extension' => $extn, 'message' => $strdnd);
 222          }
 223          $ret = array('files' => $files);
 224      } else {
 225          $ret = array();
 226      }
 227  
 228      $strdndtext = get_string('dnduploadlabeltext', 'mod_label');
 229      return array_merge($ret, array('types' => array(
 230          array('identifier' => 'text/html', 'message' => $strdndtext, 'noname' => true),
 231          array('identifier' => 'text', 'message' => $strdndtext, 'noname' => true)
 232      )));
 233  }
 234  
 235  /**
 236   * Handle a file that has been uploaded
 237   * @param object $uploadinfo details of the file / content that has been uploaded
 238   * @return int instance id of the newly created mod
 239   */
 240  function label_dndupload_handle($uploadinfo) {
 241      global $USER;
 242  
 243      // Gather the required info.
 244      $data = new stdClass();
 245      $data->course = $uploadinfo->course->id;
 246      $data->name = $uploadinfo->displayname;
 247      $data->intro = '';
 248      $data->introformat = FORMAT_HTML;
 249      $data->coursemodule = $uploadinfo->coursemodule;
 250  
 251      // Extract the first (and only) file from the file area and add it to the label as an img tag.
 252      if (!empty($uploadinfo->draftitemid)) {
 253          $fs = get_file_storage();
 254          $draftcontext = context_user::instance($USER->id);
 255          $context = context_module::instance($uploadinfo->coursemodule);
 256          $files = $fs->get_area_files($draftcontext->id, 'user', 'draft', $uploadinfo->draftitemid, '', false);
 257          if ($file = reset($files)) {
 258              if (file_mimetype_in_typegroup($file->get_mimetype(), 'web_image')) {
 259                  // It is an image - resize it, if too big, then insert the img tag.
 260                  $config = get_config('label');
 261                  $data->intro = label_generate_resized_image($file, $config->dndresizewidth, $config->dndresizeheight);
 262              } else {
 263                  // We aren't supposed to be supporting non-image types here, but fallback to adding a link, just in case.
 264                  $url = moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename());
 265                  $data->intro = html_writer::link($url, $file->get_filename());
 266              }
 267              $data->intro = file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_label', 'intro', 0,
 268                                                        null, $data->intro);
 269          }
 270      } else if (!empty($uploadinfo->content)) {
 271          $data->intro = $uploadinfo->content;
 272          if ($uploadinfo->type != 'text/html') {
 273              $data->introformat = FORMAT_PLAIN;
 274          }
 275      }
 276  
 277      return label_add_instance($data, null);
 278  }
 279  
 280  /**
 281   * Resize the image, if required, then generate an img tag and, if required, a link to the full-size image
 282   * @param stored_file $file the image file to process
 283   * @param int $maxwidth the maximum width allowed for the image
 284   * @param int $maxheight the maximum height allowed for the image
 285   * @return string HTML fragment to add to the label
 286   */
 287  function label_generate_resized_image(stored_file $file, $maxwidth, $maxheight) {
 288      global $CFG;
 289  
 290      $fullurl = moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename());
 291      $link = null;
 292      $attrib = array('alt' => $file->get_filename(), 'src' => $fullurl);
 293  
 294      if ($imginfo = $file->get_imageinfo()) {
 295          // Work out the new width / height, bounded by maxwidth / maxheight
 296          $width = $imginfo['width'];
 297          $height = $imginfo['height'];
 298          if (!empty($maxwidth) && $width > $maxwidth) {
 299              $height *= (float)$maxwidth / $width;
 300              $width = $maxwidth;
 301          }
 302          if (!empty($maxheight) && $height > $maxheight) {
 303              $width *= (float)$maxheight / $height;
 304              $height = $maxheight;
 305          }
 306  
 307          $attrib['width'] = $width;
 308          $attrib['height'] = $height;
 309  
 310          // If the size has changed and the image is of a suitable mime type, generate a smaller version
 311          if ($width != $imginfo['width']) {
 312              $mimetype = $file->get_mimetype();
 313              if ($mimetype === 'image/gif' or $mimetype === 'image/jpeg' or $mimetype === 'image/png') {
 314                  require_once($CFG->libdir.'/gdlib.php');
 315                  $data = $file->generate_image_thumbnail($width, $height);
 316  
 317                  if (!empty($data)) {
 318                      $fs = get_file_storage();
 319                      $record = array(
 320                          'contextid' => $file->get_contextid(),
 321                          'component' => $file->get_component(),
 322                          'filearea'  => $file->get_filearea(),
 323                          'itemid'    => $file->get_itemid(),
 324                          'filepath'  => '/',
 325                          'filename'  => 's_'.$file->get_filename(),
 326                      );
 327                      $smallfile = $fs->create_file_from_string($record, $data);
 328  
 329                      // Replace the image 'src' with the resized file and link to the original
 330                      $attrib['src'] = moodle_url::make_draftfile_url($smallfile->get_itemid(), $smallfile->get_filepath(),
 331                                                                      $smallfile->get_filename());
 332                      $link = $fullurl;
 333                  }
 334              }
 335          }
 336  
 337      } else {
 338          // Assume this is an image type that get_imageinfo cannot handle (e.g. SVG)
 339          $attrib['width'] = $maxwidth;
 340      }
 341  
 342      $attrib['class'] = "img-fluid";
 343      $img = html_writer::empty_tag('img', $attrib);
 344      if ($link) {
 345          return html_writer::link($link, $img);
 346      } else {
 347          return $img;
 348      }
 349  }
 350  
 351  /**
 352   * Check if the module has any update that affects the current user since a given time.
 353   *
 354   * @param  cm_info $cm course module data
 355   * @param  int $from the time to check updates from
 356   * @param  array $filter  if we need to check only specific updates
 357   * @return stdClass an object with the different type of areas indicating if they were updated or not
 358   * @since Moodle 3.2
 359   */
 360  function label_check_updates_since(cm_info $cm, $from, $filter = array()) {
 361      $updates = course_check_module_updates_since($cm, $from, array(), $filter);
 362      return $updates;
 363  }
 364  
 365  /**
 366   * This function receives a calendar event and returns the action associated with it, or null if there is none.
 367   *
 368   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
 369   * is not displayed on the block.
 370   *
 371   * @param calendar_event $event
 372   * @param \core_calendar\action_factory $factory
 373   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
 374   * @return \core_calendar\local\event\entities\action_interface|null
 375   */
 376  function mod_label_core_calendar_provide_event_action(calendar_event $event,
 377                                                        \core_calendar\action_factory $factory,
 378                                                        int $userid = 0) {
 379      $cm = get_fast_modinfo($event->courseid, $userid)->instances['label'][$event->instance];
 380  
 381      if (!$cm->uservisible) {
 382          // The module is not visible to the user for any reason.
 383          return null;
 384      }
 385  
 386      $completion = new \completion_info($cm->get_course());
 387  
 388      $completiondata = $completion->get_data($cm, false, $userid);
 389  
 390      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
 391          return null;
 392      }
 393  
 394      return $factory->create_instance(
 395          get_string('view'),
 396          new \moodle_url('/mod/label/view.php', ['id' => $cm->id]),
 397          1,
 398          true
 399      );
 400  }