Fixed a notice. Tidied up format class call a bit. Added provision
[moodle.git] / question / import.php
1 <?php // $Id$
2 /**
3 * Import quiz questions into the given category
4 *
5 * @version $Id$
6 * @author Martin Dougiamas, Howard Miller, and many others.
7 *         {@link http://moodle.org}
8 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
9 * @package quiz
10 */
12     require_once("../config.php");
13     require_once( "editlib.php" );
14     require_once($CFG->dirroot.'/lib/uploadlib.php');
16     // get parameters
17     $params = new stdClass;
18     $params->choosefile = optional_param('choosefile','',PARAM_PATH);
19     $categoryid = optional_param('category', 0, PARAM_INT);
20     $catfromfile = optional_param('catfromfile', 0, PARAM_BOOL );
21     $courseid = optional_param('course', 0, PARAM_INT);
22     $format = optional_param('format','',PARAM_FILE);
23     $params->matchgrades = optional_param('matchgrades','',PARAM_ALPHA);
25     // get display strings
26     $txt = new stdClass();
27     $txt->category = get_string('category','quiz');
28     $txt->choosefile = get_string('choosefile','quiz');
29     $txt->editingquiz = get_string(isset($SESSION->modform->instance) ? "editingquiz" : "editquestions", "quiz");
30     $txt->file = get_string('file');
31     $txt->fileformat = get_string('fileformat','quiz');
32     $txt->fromfile = get_string('fromfile','quiz');
33     $txt->importcategory = get_string('importcategory','quiz');
34     $txt->importerror = get_string('importerror','quiz');
35     $txt->importfilearea = get_string('importfilearea','quiz');
36     $txt->importfileupload = get_string('importfileupload','quiz');
37     $txt->importfromthisfile = get_string('importfromthisfile','quiz');
38     $txt->importquestions = get_string("importquestions", "quiz");
39     $txt->matchgrades = get_string('matchgrades','quiz');
40     $txt->matchgradeserror = get_string('matchgradeserror','quiz');
41     $txt->matchgradesnearest = get_string('matchgradesnearest','quiz');
42     $txt->modulename = get_string('modulename','quiz');
43     $txt->modulenameplural = get_string('modulenameplural','quiz');
44     $txt->nocategory = get_string('nocategory','quiz');
45     $txt->onlyteachersimport = get_string('onlyteachersimport','quiz');
46     $txt->questions = get_string("questions", "quiz");
47     $txt->quizzes = get_string('modulenameplural', 'quiz');
48     $txt->upload = get_string('upload');
49     $txt->uploadproblem = get_string('uploadproblem');
50     $txt->uploadthisfile = get_string('uploadthisfile');
52     // matching options
53     $matchgrades = array();
54     $matchgrades['error'] = $txt->matchgradeserror;
55     $matchgrades['nearest'] = $txt->matchgradesnearest;
57     if ($categoryid) { // update category in session variable
58         $SESSION->questioncat = $categoryid;
59     } else { // try to get category from modform
60         $showcatmenu = true; // will ensure that user can choose category
61         if (isset($SESSION->questioncat)) {
62             $categoryid = $SESSION->questioncat;
63         }
64     }
66     if (! $category = get_record("question_categories", "id", $categoryid)) {
67         // if no valid category was given, use the default category
68         if ($courseid) {
69             $category = get_default_question_category($courseid);
70         } else {
71             error( $txt->nocategory );
72         }
73     }
75     if (!$courseid) { // need to get the course from the chosen category
76         $courseid = $category->course;
77     }
79     if (! $course = get_record("course", "id", $courseid)) {
80         error("Invalid course!");
81     }
83     require_login($course->id, false);
85     require_capability('moodle/question:import', get_context_instance(CONTEXT_COURSE, $course->id));
87     // ensure the files area exists for this course
88     make_upload_directory( "$course->id" );
91     //==========
92     // PAGE HEADER
93     //==========
95     if (isset($SESSION->modform->instance) and $quiz = get_record('quiz', 'id', $SESSION->modform->instance)) {
96         $strupdatemodule = has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))
97             ? update_module_button($SESSION->modform->cmid, $course->id, $txt->modulename)
98             : "";
99         print_header_simple($txt->importquestions, '',
100                  "<a href=\"$CFG->wwwroot/mod/quiz/index.php?id=$course->id\">".$txt->modulenameplural.'</a>'.
101                  " -> <a href=\"$CFG->wwwroot/mod/quiz/view.php?q=$quiz->id\">".format_string($quiz->name).'</a>'.
102                  ' -> '.$txt->importquestions,
103                  "", "", true, $strupdatemodule);
104         $currenttab = 'edit';
105         $mode = 'import';
106         include($CFG->dirroot.'/mod/quiz/tabs.php');
107     } else {
108         print_header_simple($txt->importquestions, '', $txt->importquestions);
109         // print tabs
110         $currenttab = 'import';
111         include('tabs.php');
112     }
115     // file upload form sumitted
116     if (!empty($format) and confirm_sesskey() ) { 
118         // file checks out ok
119         $fileisgood = false;
121         // work out if this is an uploaded file 
122         // or one from the filesarea.
123         if (!empty($params->choosefile)) {
124             $importfile = "{$CFG->dataroot}/{$course->id}/{$params->choosefile}";
125             if (file_exists($importfile)) {
126                 $fileisgood = true;
127             }
128             else {
129                 notify($txt->uploadproblem);
130             }
131         }
132         else {
133             // must be upload file
134             if (empty($_FILES['newfile'])) {
135                 notify( $txt->uploadproblem );
136             }
137             else if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) {
138                 notify( $txt->uploadproblem );
139             }
140             else {
141                 $importfile = $_FILES['newfile']['tmp_name'];
142                 $fileisgood = true;
143             }
144         }
146         // process if we are happy file is ok
147         if ($fileisgood) { 
149             if (! is_readable("format/$format/format.php")) {
150                 error( get_string('formatnotfound','quiz', $format) );
151             }
153             require("format.php");  // Parent class
154             require("format/$format/format.php");
156             $classname = "qformat_$format";
157             $qformat = new $classname();
159             // load data into class
160             $qformat->setCategory( $category );
161             $qformat->setCourse( $course );
162             $qformat->setFilename( $importfile );
163             $qformat->setMatchgrades( $params->matchgrades );
164             $qformat->setCatfromfile( $catfromfile );
166             if (! $qformat->importpreprocess()) {             // Do anything before that we need to
167                 error( $txt->importerror ,
168                       "$CFG->wwwroot/question/import.php?courseid={$course->id}&amp;category=$category->id");
169             }
171             if (! $qformat->importprocess() ) {     // Process the uploaded file
172                 error( $txt->importerror ,
173                       "$CFG->wwwroot/question/import.php?courseid={$course->id}&amp;category=$category->id");
174             }
176             if (! $qformat->importpostprocess()) {                     // In case anything needs to be done after
177                 error( $txt->importerror ,
178                       "$CFG->wwwroot/question/import.php?courseid={$course->id}&amp;category=$category->id");
179             }
181             echo "<hr />";
182             print_continue("edit.php?courseid=$course->id");
183             print_footer($course);
184             exit;
185         }
186     }
188     /// Print upload form
190     // get list of available import formats
191     $fileformatnames = get_import_export_formats( 'import' );
193     print_heading_with_help($txt->importquestions, "import", "quiz");
195     /// Get all the existing categories now
196     if (has_capability('moodle/question:manage', get_context_instance(CONTEXT_SYSTEM, SITEID))) { // the admin can import into all categories
197         if (!$categories = get_records_select("question_categories", "course = '{$course->id}' OR publish = '1'", "parent, sortorder, name ASC")) {
198             error("Could not find any question categories!"); // Something is really wrong
199         }
200     } else { // select only the categories to which the teacher has write access
201         $cats = get_records('question_categories');
202         $categories = array();
203         foreach ($cats as $cat) {
204             if (has_capability('moodle/question:managecategory', get_context_instance(CONTEXT_COURSE, $cat->course))) {
205                 $categories[] = $cat;
206             }      
207         }
208         if (empty($categories)) {
209             error("Could not find any question categories!");
210         }
211     }
212     $categories = add_indented_names($categories);
213     foreach ($categories as $key => $cat) {
214        if ($catcourse = get_record("course", "id", $cat->course)) {
215            if ($cat->publish && $cat->course != $course->id) {
216                $cat->indentedname .= " ($catcourse->shortname)";
217            }
218            $catmenu[$cat->id] = $cat->indentedname;
219        }
220     }
221    
222     //==========
223     // DISPLAY
224     //==========
225  
226     ?>
228     <form name="form" enctype="multipart/form-data" method="post" action="import.php">
229         <input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" />
230         <?php print_simple_box_start("center"); ?>
231         <table cellpadding="5">
232             <tr>
233                 <td align="right"><?php echo $txt->category; ?>:</td>
234                 <td><?php choose_from_menu($catmenu, "category", $category->id, ""); ?>
235                     <?php echo $txt->fromfile; ?>
236                     <input name="catfromfile" type="checkbox" />
237                     <?php helpbutton('importcategory', $txt->importcategory, 'quiz'); ?></td>
238             </tr>
240             <tr>
241                 <td align="right"><?php echo $txt->fileformat; ?>:</td>
242                 <td><?php choose_from_menu($fileformatnames, "format", "gift", "");
243                     helpbutton("import", $txt->importquestions, "quiz"); ?></td>
244             </tr>
245             <tr>
246                 <td align="right"><?php echo $txt->matchgrades; ?></td>
247                 <td><?php choose_from_menu($matchgrades,'matchgrades',$txt->matchgradeserror,'' );
248                     helpbutton('matchgrades', $txt->matchgrades, 'quiz'); ?></td>
249             </td>
250         </table>
251         <?php
252         print_simple_box_end();
254         print_simple_box_start('center'); ?>
255         <?php echo $txt->importfileupload; ?>
256         <table cellpadding="5">
257             <tr>
258                 <td align="right"><?php echo $txt->upload; ?>:</td>
259                 <td><?php upload_print_form_fragment(1,array('newfile'),null,false,null,$course->maxbytes,0,false); ?></td>
260             </tr>
262             <tr>
263                 <td>&nbsp;</td>
264                 <td><input type="submit" name="save" value="<?php echo $txt->uploadthisfile; ?>" /></td>
265             </tr>
266         </table>
267         <?php
268         print_simple_box_end();
270         print_simple_box_start('center'); ?>
271         <?php echo $txt->importfilearea; ?>
272         <table cellpadding="5">
273             <tr>
274                 <td align="right"><?php echo $txt->file; ?>:</td>
275                 <td><input type="text" name="choosefile" size="50" /></td>
276             </tr>
278             <tr>
279                 <td>&nbsp;</td>
280                 <td><?php  button_to_popup_window ("/files/index.php?id={$course->id}&amp;choose=form.choosefile", 
281                     "coursefiles", $txt->choosefile, 500, 750, $txt->choosefile); ?>
282                     <input type="submit" name="save" value="<?php echo $txt->importfromthisfile; ?>" /></td>
283             </tr>
284         </table>
285         <?php 
286         print_simple_box_end(); ?>
287     </form>
289     <?php
290     print_footer($course);
292 ?>