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.

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

   1  <?php
   2  ///////////////////////////////////////////////////////////////////////////
   3  //                                                                       //
   4  // NOTICE OF COPYRIGHT                                                   //
   5  //                                                                       //
   6  // Moodle - Modular Object-Oriented Dynamic Learning Environment         //
   7  //          http://moodle.org                                            //
   8  //                                                                       //
   9  // Copyright (C) 1999-onwards Moodle Pty Ltd  http://moodle.com          //
  10  //                                                                       //
  11  // This program is free software; you can redistribute it and/or modify  //
  12  // it under the terms of the GNU General Public License as published by  //
  13  // the Free Software Foundation; either version 2 of the License, or     //
  14  // (at your option) any later version.                                   //
  15  //                                                                       //
  16  // This program is distributed in the hope that it will be useful,       //
  17  // but WITHOUT ANY WARRANTY; without even the implied warranty of        //
  18  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
  19  // GNU General Public License for more details:                          //
  20  //                                                                       //
  21  //          http://www.gnu.org/copyleft/gpl.html                         //
  22  //                                                                       //
  23  ///////////////////////////////////////////////////////////////////////////
  24  
  25  class data_field_picture extends data_field_base {
  26      var $type = 'picture';
  27      var $previewwidth  = 50;
  28      var $previewheight = 50;
  29  
  30      function display_add_field($recordid = 0, $formdata = null) {
  31          global $CFG, $DB, $OUTPUT, $USER, $PAGE;
  32  
  33          $file        = false;
  34          $content     = false;
  35          $alttext     = '';
  36          $itemid = null;
  37          $fs = get_file_storage();
  38  
  39          if ($formdata) {
  40              $fieldname = 'field_' . $this->field->id . '_file';
  41              $itemid = clean_param($formdata->$fieldname, PARAM_INT);
  42              $fieldname = 'field_' . $this->field->id . '_alttext';
  43              if (isset($formdata->$fieldname)) {
  44                  $alttext = $formdata->$fieldname;
  45              }
  46          } else if ($recordid) {
  47              if (!$content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
  48                  // Quickly make one now!
  49                  $content = new stdClass();
  50                  $content->fieldid  = $this->field->id;
  51                  $content->recordid = $recordid;
  52                  $id = $DB->insert_record('data_content', $content);
  53                  $content = $DB->get_record('data_content', array('id' => $id));
  54              }
  55              file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
  56              if (!empty($content->content)) {
  57                  if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
  58                      $usercontext = context_user::instance($USER->id);
  59  
  60                      if ($thumbfile = $fs->get_file($usercontext->id, 'user', 'draft', $itemid, '/', 'thumb_'.$content->content)) {
  61                          $thumbfile->delete();
  62                      }
  63                  }
  64              }
  65              $alttext = $content->content1;
  66          } else {
  67              $itemid = file_get_unused_draft_itemid();
  68          }
  69          $str = '<div title="' . s($this->field->description) . '">';
  70          $str .= '<fieldset><legend><span class="accesshide">'.$this->field->name;
  71  
  72          if ($this->field->required) {
  73              $str .= '&nbsp;' . get_string('requiredelement', 'form') . '</span></legend>';
  74              $image = $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'));
  75              $str .= html_writer::div($image, 'inline-req');
  76          } else {
  77              $str .= '</span></legend>';
  78          }
  79          $str .= '<noscript>';
  80          if ($file) {
  81              $src = file_encode_url($CFG->wwwroot.'/pluginfile.php/', $this->context->id.'/mod_data/content/'.$content->id.'/'.$file->get_filename());
  82              $str .= '<img width="'.s($this->previewwidth).'" height="'.s($this->previewheight).'" src="'.$src.'" alt="" />';
  83          }
  84          $str .= '</noscript>';
  85  
  86          $options = new stdClass();
  87          $options->maxbytes  = $this->field->param3;
  88          $options->maxfiles  = 1; // Only one picture permitted.
  89          $options->itemid    = $itemid;
  90          $options->accepted_types = array('web_image');
  91          $options->return_types = FILE_INTERNAL;
  92          $options->context = $PAGE->context;
  93          if (!empty($file)) {
  94              $options->filename = $file->get_filename();
  95              $options->filepath = '/';
  96          }
  97  
  98          $fm = new form_filemanager($options);
  99          // Print out file manager.
 100  
 101          $output = $PAGE->get_renderer('core', 'files');
 102          $str .= '<div class="mod-data-input">';
 103          $str .= $output->render($fm);
 104  
 105          $str .= '<div class="mdl-left">';
 106          $str .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . s($itemid) . '" />';
 107          $str .= '<label for="field_' . $this->field->id . '_alttext">' .
 108                  get_string('alttext', 'data') .
 109                  '</label>&nbsp;<input type="text" class="form-control" name="field_' .
 110                  $this->field->id . '_alttext" id="field_' . $this->field->id . '_alttext" value="' . s($alttext) . '" />';
 111          $str .= '</div>';
 112          $str .= '</div>';
 113  
 114          $str .= '</fieldset>';
 115          $str .= '</div>';
 116  
 117          return $str;
 118      }
 119  
 120      // TODO delete this function and instead subclass data_field_file - see MDL-16493
 121  
 122      function get_file($recordid, $content=null) {
 123          global $DB;
 124          if (empty($content)) {
 125              if (!$content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
 126                  return null;
 127              }
 128          }
 129          $fs = get_file_storage();
 130          if (!$file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
 131              return null;
 132          }
 133  
 134          return $file;
 135      }
 136  
 137      function display_search_field($value = '') {
 138          return '<label class="accesshide" for="f_' . $this->field->id . '">' . get_string('fieldname', 'data') . '</label>' .
 139                 '<input type="text" size="16" id="f_' . $this->field->id . '" name="f_' . $this->field->id . '" ' .
 140                 'value="' . s($value) . '" class="form-control"/>';
 141      }
 142  
 143      public function parse_search_field($defaults = null) {
 144          $param = 'f_'.$this->field->id;
 145          if (empty($defaults[$param])) {
 146              $defaults = array($param => '');
 147          }
 148          return optional_param($param, $defaults[$param], PARAM_NOTAGS);
 149      }
 150  
 151      function generate_sql($tablealias, $value) {
 152          global $DB;
 153  
 154          static $i=0;
 155          $i++;
 156          $name = "df_picture_$i";
 157          return array(" ({$tablealias}.fieldid = {$this->field->id} AND ".$DB->sql_like("{$tablealias}.content", ":$name", false).") ", array($name=>"%$value%"));
 158      }
 159  
 160      function display_browse_field($recordid, $template) {
 161          global $CFG, $DB;
 162  
 163          if (!$content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
 164              return false;
 165          }
 166  
 167          if (empty($content->content)) {
 168              return '';
 169          }
 170  
 171          $alt   = $content->content1;
 172          $title = $alt;
 173  
 174          if ($template == 'listtemplate') {
 175              $src = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_data/content/'.$content->id.'/'.'thumb_'.$content->content);
 176              // no need to add width/height, because the thumb is resized properly
 177              $str = '<a href="view.php?d='.$this->field->dataid.'&amp;rid='.$recordid.'"><img src="'.$src.'" alt="'.s($alt).'" title="'.s($title).'" class="list_picture"/></a>';
 178  
 179          } else {
 180              $src = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_data/content/'.$content->id.'/'.$content->content);
 181              $width  = $this->field->param1 ? ' width="'.s($this->field->param1).'" ':' ';
 182              $height = $this->field->param2 ? ' height="'.s($this->field->param2).'" ':' ';
 183              $str = '<a href="'.$src.'"><img '.$width.$height.' src="'.$src.'" alt="'.s($alt).'" title="'.s($title).'" class="list_picture"/></a>';
 184          }
 185  
 186          return $str;
 187      }
 188  
 189      function update_field() {
 190          global $DB, $OUTPUT;
 191  
 192          // Get the old field data so that we can check whether the thumbnail dimensions have changed
 193          $oldfield = $DB->get_record('data_fields', array('id'=>$this->field->id));
 194          $DB->update_record('data_fields', $this->field);
 195  
 196          // Have the thumbnail dimensions changed?
 197          if ($oldfield && ($oldfield->param4 != $this->field->param4 || $oldfield->param5 != $this->field->param5)) {
 198              // Check through all existing records and update the thumbnail
 199              if ($contents = $DB->get_records('data_content', array('fieldid'=>$this->field->id))) {
 200                  $fs = get_file_storage();
 201                  if (count($contents) > 20) {
 202                      echo $OUTPUT->notification(get_string('resizingimages', 'data'), 'notifysuccess');
 203                      echo "\n\n";
 204                      // To make sure that ob_flush() has the desired effect
 205                      ob_flush();
 206                  }
 207                  foreach ($contents as $content) {
 208                      if (!$file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
 209                          continue;
 210                      }
 211                      if ($thumbfile = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', 'thumb_'.$content->content)) {
 212                          $thumbfile->delete();
 213                      }
 214                      core_php_time_limit::raise(300);
 215                      // Might be slow!
 216                      $this->update_thumbnail($content, $file);
 217                  }
 218              }
 219          }
 220          return true;
 221      }
 222  
 223      function update_content($recordid, $value, $name='') {
 224          global $CFG, $DB, $USER;
 225  
 226          // Should always be available since it is set by display_add_field before initializing the draft area.
 227          $content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid));
 228          if (!$content) {
 229              $content = (object)array('fieldid' => $this->field->id, 'recordid' => $recordid);
 230              $content->id = $DB->insert_record('data_content', $content);
 231          }
 232  
 233          $names = explode('_', $name);
 234          switch ($names[2]) {
 235              case 'file':
 236                  $fs = get_file_storage();
 237                  file_save_draft_area_files($value, $this->context->id, 'mod_data', 'content', $content->id);
 238                  $usercontext = context_user::instance($USER->id);
 239                  $files = $fs->get_area_files(
 240                      $this->context->id,
 241                      'mod_data', 'content',
 242                      $content->id,
 243                      'itemid, filepath, filename',
 244                      false);
 245  
 246                  // We expect no or just one file (maxfiles = 1 option is set for the form_filemanager).
 247                  if (count($files) == 0) {
 248                      $content->content = null;
 249                  } else {
 250                      $file = array_values($files)[0];
 251  
 252                      if (count($files) > 1) {
 253                          // This should not happen with a consistent database. Inform admins/developers about the inconsistency.
 254                          debugging('more then one file found in mod_data instance {$this->data->id} picture field (field id: {$this->field->id}) area during update data record {$recordid} (content id: {$content->id})', DEBUG_NORMAL);
 255                      }
 256  
 257                      if ($file->get_imageinfo() === false) {
 258                          $url = new moodle_url('/mod/data/edit.php', array('d' => $this->field->dataid));
 259                          redirect($url, get_string('invalidfiletype', 'error', $file->get_filename()));
 260                      }
 261                      $content->content = $file->get_filename();
 262                      $this->update_thumbnail($content, $file);
 263                  }
 264                  $DB->update_record('data_content', $content);
 265  
 266                  break;
 267  
 268              case 'alttext':
 269                  // only changing alt tag
 270                  $content->content1 = clean_param($value, PARAM_NOTAGS);
 271                  $DB->update_record('data_content', $content);
 272                  break;
 273  
 274              default:
 275                  break;
 276          }
 277      }
 278  
 279      function update_thumbnail($content, $file) {
 280          // (Re)generate thumbnail image according to the dimensions specified in the field settings.
 281          // If thumbnail width and height are BOTH not specified then no thumbnail is generated, and
 282          // additionally an attempted delete of the existing thumbnail takes place.
 283          $fs = get_file_storage();
 284          $file_record = array('contextid'=>$file->get_contextid(), 'component'=>$file->get_component(), 'filearea'=>$file->get_filearea(),
 285                               'itemid'=>$file->get_itemid(), 'filepath'=>$file->get_filepath(),
 286                               'filename'=>'thumb_'.$file->get_filename(), 'userid'=>$file->get_userid());
 287          try {
 288              // this may fail for various reasons
 289              $fs->convert_image($file_record, $file, $this->field->param4, $this->field->param5, true);
 290              return true;
 291          } catch (Exception $e) {
 292              debugging($e->getMessage());
 293              return false;
 294          }
 295      }
 296  
 297      function text_export_supported() {
 298          return false;
 299      }
 300  
 301      function file_ok($path) {
 302          return true;
 303      }
 304  
 305      /**
 306       * Custom notempty function
 307       *
 308       * @param string $value
 309       * @param string $name
 310       * @return bool
 311       */
 312      function notemptyfield($value, $name) {
 313          global $USER;
 314  
 315          $names = explode('_', $name);
 316          if ($names[2] == 'file') {
 317              $usercontext = context_user::instance($USER->id);
 318              $fs = get_file_storage();
 319              $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $value);
 320              return count($files) >= 2;
 321          }
 322          return false;
 323      }
 324  
 325      /**
 326       * Return the plugin configs for external functions.
 327       *
 328       * @return array the list of config parameters
 329       * @since Moodle 3.3
 330       */
 331      public function get_config_for_external() {
 332          // Return all the config parameters.
 333          $configs = [];
 334          for ($i = 1; $i <= 10; $i++) {
 335              $configs["param$i"] = $this->field->{"param$i"};
 336          }
 337          return $configs;
 338      }
 339  }