Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/mod/label/ -> lib.php (source)

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

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