Assignment MDL-7206 - download all submissions as a zip - finally pushing this into...
[moodle.git] / mod / assignment / type / uploadsingle / assignment.class.php
index a4c1cbe..1193721 100644 (file)
@@ -229,6 +229,56 @@ class assignment_uploadsingle extends assignment_base {
             }
         }
     }
+
+    /**
+     * creates a zip of all assignment submissions and sends a zip to the browser
+     */
+    function download_submissions() {
+        global $CFG,$DB;
+        require_once($CFG->libdir.'/filelib.php');
+
+        $submissions = $this->get_submissions('','');
+        if (empty($submissions)) {
+            error("there are no submissions to download");
+        }
+        $filesforzipping = array();
+        $filenewname = clean_filename($this->assignment->name); //create prefix of individual files
+        $tempdir = assignment_create_temp_dir($CFG->dataroot."/temp/", "assignment".$this->assignment->id); //location for temp files.
+        $fs = get_file_storage();
+
+        $groupmode = groupmode($this->course,$this->cm);
+        $groupid = 0;   // All users
+        $groupname = '';
+        if($groupmode) {
+            $group = get_current_group($this->course->id, true);
+            $groupid = $group->id;
+            $groupname = $group->name.'-';
+        }
+        $filename = str_replace(' ', '_', clean_filename($this->course->shortname.'-'.$this->assignment->name.'-'.$groupname.$this->assignment->id.".zip")); //name of new zip file.
+        foreach ($submissions as $submission) {
+            $a_userid = $submission->userid; //get userid
+            if ((groups_is_member($groupid,$a_userid)or !$groupmode or !$groupid)) {
+                $a_assignid = $submission->assignment; //get name of this assignment for use in the file names.
+                $a_user = $DB->get_record("user", array("id"=>$a_userid),'id,username,firstname,lastname'); //get user firstname/lastname
+                
+                $files = $fs->get_area_files($this->context->id, 'assignment_submission', $a_userid, "timemodified", false);
+                foreach ($files as $file) {
+                    //get files new name.
+                    $fileforzipname =  $a_user->username . "_" . $filenewname . "_" . $file->get_filename();
+                    //get files old name
+                    if (!$file->copy_content_to($tempdir . $fileforzipname)) {
+                        error ("failed to copy file<br>" .$tempdir. $fileforzipname);
+                    }
+                    //save file name to array for zipping.
+                    $filesforzipping[$fileforzipname] = $tempdir.$fileforzipname;
+                }
+            }
+        } // End of foreach
+        if ($zipfile = assignment_pack_files($filesforzipping)) {
+            remove_dir($tempdir); //remove old tempdir with individual files.
+            send_temp_file($zipfile, $filename); //send file and delete after sending.
+        }
+    }
 }