Example #1
0
 /**
  * @param string $courseshortname
  * @param string $data
  * @param string $filename
  * @return array
  * @throws \file_exception
  * @throws \stored_file_creation_exception
  */
 public function setcoverimage($courseshortname, $data, $filename)
 {
     global $CFG;
     $course = $this->coursebyshortname($courseshortname);
     if ($course->id != SITEID) {
         // Course cover images.
         $context = \context_course::instance($course->id);
     } else {
         // Site cover images.
         $context = \context_system::instance();
     }
     require_capability('moodle/course:changesummary', $context);
     $fs = get_file_storage();
     $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
     $ext = $ext === 'jpeg' ? 'jpg' : $ext;
     if (!in_array($ext, local::supported_coverimage_types())) {
         return ['success' => false, 'warning' => get_string('unsupportedcoverimagetype', 'theme_snap', $ext)];
     }
     $newfilename = 'rawcoverimage.' . $ext;
     $binary = base64_decode($data);
     if (strlen($binary) > get_max_upload_file_size($CFG->maxbytes)) {
         throw new \moodle_exception('error:coverimageexceedsmaxbytes', 'theme_snap');
     }
     if ($course->id != SITEID) {
         // Course cover images.
         $context = \context_course::instance($course->id);
         // Check suitability of course summary files area for use with cover images.
         if (!$this->check_summary_files_for_image_suitability($context)) {
             return ['success' => false, 'warning' => get_string('coursesummaryfilesunsuitable', 'theme_snap')];
         }
         $fileinfo = array('contextid' => $context->id, 'component' => 'course', 'filearea' => 'overviewfiles', 'itemid' => 0, 'filepath' => '/', 'filename' => $newfilename);
         // Remove any old course summary image files.
         $fs->delete_area_files($context->id, $fileinfo['component'], $fileinfo['filearea']);
     } else {
         // Site cover images.
         $context = \context_system::instance();
         $fileinfo = array('contextid' => $context->id, 'component' => 'theme_snap', 'filearea' => 'poster', 'itemid' => 0, 'filepath' => '/', 'filename' => $newfilename);
         // Remove everything from poster area.
         $fs->delete_area_files($context->id, 'theme_snap', 'poster');
     }
     // Create new cover image file and process it.
     $storedfile = $fs->create_file_from_string($fileinfo, $binary);
     $success = $storedfile instanceof \stored_file;
     if ($course->id != SITEID) {
         local::process_coverimage($context, $storedfile);
     } else {
         set_config('poster', $newfilename, 'theme_snap');
         local::process_coverimage($context);
     }
     return ['success' => $success];
 }