/**
 * Update certificate instance.
 * 
 * @param stdClass $certificate
 * @return bool true
 */
function simplecertificate_update_instance(stdclass $data)
{
    global $DB, $CFG;
    require_once $CFG->dirroot . '/mod/simplecertificate/locallib.php';
    $context = context_module::instance($data->coursemodule);
    $simplecertificate = new simplecertificate($context, null, null);
    return $simplecertificate->update_instance($data);
}
 /**
  * Overwrites parents to format $formdata
  * @see simplecertificate::update_instance()
  */
 public function update_instance(stdClass $instance)
 {
     global $CFG, $USER;
     //usercontext
     $user_context = context_user::instance($USER->id);
     // Draft fileinfo
     $fileinfo = array('contextid' => $user_context->id, 'component' => 'user', 'filearea' => 'draft', 'filepath' => '/');
     $formdata = clone $instance;
     unset($formdata->certificatetext);
     unset($formdata->certificatetextformat);
     $formdata->certificatetext['text'] = $instance->certificatetext;
     $formdata->certificatetext['format'] = $instance->certificatetextformat;
     if (!empty($instance->secondpagetext)) {
         unset($formdata->secondpagetext);
         unset($formdata->secondpagetextformat);
         $formdata->secondpagetext['text'] = $instance->secondpagetext;
         $formdata->secondpagetext['format'] = $instance->secondpagetextformat;
     }
     $fs = get_file_storage();
     if (!empty($instance->certificateimage)) {
         $imagefileinfo = self::get_certificate_image_fileinfo($this->get_context()->id);
         $imagefile = $fs->get_file($imagefileinfo['contextid'], $imagefileinfo['component'], $imagefileinfo['filearea'], $imagefileinfo['itemid'], $imagefileinfo['filepath'], $instance->certificateimage);
         $fileinfo['itemid'] = rand(1, 10);
         $fs->delete_area_files($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid']);
         $fs->create_file_from_storedfile($fileinfo, $imagefile);
         $formdata->certificateimage = $fileinfo['itemid'];
         $imagefileinfo = null;
     }
     if (!empty($instance->secondimage)) {
         $imagefileinfo = self::get_certificate_secondimage_fileinfo($this->get_context()->id);
         $imagefile = $fs->get_file($imagefileinfo['contextid'], $imagefileinfo['component'], $imagefileinfo['filearea'], $imagefileinfo['itemid'], $imagefileinfo['filepath'], $instance->secondimage);
         $fileinfo['itemid'] = rand(11, 21);
         $fs->delete_area_files($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid']);
         $fs->create_file_from_storedfile($fileinfo, $imagefile);
         $formdata->secondimage = $fileinfo['itemid'];
         $imagefileinfo = null;
     }
     parent::update_instance($formdata);
 }