public static function rotate_page($assignment, $userid, $attemptnumber, $index, $rotateleft) {
        $assignment = self::get_assignment_from_param($assignment);
        $grade = $assignment->get_user_grade($userid, true, $attemptnumber);
        // Check permission.
        if (!$assignment->can_view_submission($userid)) {
            print_error('nopermission');
        }

        $filearea = self::PAGE_IMAGE_FILEAREA;
        $files = self::get_files($assignment, $userid, $attemptnumber, $filearea);
        if (!empty($files)) {
            foreach ($files as $file) {
                preg_match('/' . pdf::IMAGE_PAGE . '([\d]+)\./', $file->get_filename(), $matches);
                if (empty($matches) or !is_numeric($matches[1])) {
                    throw new \coding_exception("'" . $file->get_filename()
                        . "' file hasn't the expected format filename: image_pageXXXX.png.");
                }
                $pagenumber = (int)$matches[1];

                if ($pagenumber == $index) {
                    $source = imagecreatefromstring($file->get_content());
                    $pagerotation = page_editor::get_page_rotation($grade->id, $index);
                    $degree = empty($pagerotation) ? 0 : $pagerotation->degree;
                    if ($rotateleft) {
                        $content = imagerotate($source, 90, 0);
                        $degree = ($degree + 90) % 360;
                    } else {
                        $content = imagerotate($source, -90, 0);
                        $degree = ($degree - 90) % 360;
                    }
                    $filename = $matches[0].'png';
                    $tmpdir = make_temp_directory(self::COMPONENT . '/' . self::PAGE_IMAGE_FILEAREA . '/'
                        . self::hash($assignment, $userid, $attemptnumber));
                    $tempfile = $tmpdir . '/' . time() . '_' . $filename;
                    imagepng($content, $tempfile);

                    $filearea = self::PAGE_IMAGE_FILEAREA;
                    $newfile = self::save_file($assignment, $userid, $attemptnumber, $filearea, $tempfile);

                    unlink($tempfile);
                    rmdir($tmpdir);
                    imagedestroy($source);
                    imagedestroy($content);
                    $file->delete();
                    if (!empty($newfile)) {
                        page_editor::set_page_rotation($grade->id, $pagenumber, true, $newfile->get_pathnamehash(), $degree);
                    }
                    return $newfile;
                }
            }
        }
        return null;
    }