File: format.php

package info (click to toggle)
moodle 1.6.3-2%2Betch3
  • links: PTS
  • area: main
  • in suites: etch
  • size: 37,172 kB
  • ctags: 51,688
  • sloc: php: 231,916; sql: 5,631; xml: 2,688; sh: 1,185; perl: 638; makefile: 48; pascal: 36
file content (514 lines) | stat: -rwxr-xr-x 22,315 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<?php  // $Id: format.php,v 1.6 2006/04/10 22:10:34 gustav_delius Exp $
////////////////////////////////////////////////////////////////////
/// Class for importing course test manager questions.            //
///                                                               //
///                                                               //
////////////////////////////////////////////////////////////////////

// Based on format.php, included by ../../import.php
require_once($CFG->dirroot.'/lib/uploadlib.php');

class qformat_coursetestmanager extends qformat_default {

    function provide_import() {
      return true;
    }

    function importpreprocess($category) {
        $this->category = $category;  // Important
        return true;
    }

    function importprocess($filename) {
      global $CFG,$strimportquestions,$form,$question_category,$category,$course,
      $hostname, $mdapath, $mdbpath;
            if ((PHP_OS == "Linux") and isset($hostname)) {
                $hostname = trim($hostname);
                // test the ODBC socket server connection
                // if failure, unset hostname and set hostname_access_error
        $question_categories = $this->getquestioncategories($mdbpath, $mdapath, $hostname);
        if (!$question_categories) {
            $hostname_access_error = $hostname . " ";
            unset($hostname);
        } else  {
            $hostname_access_error = 0;
        }
            }

            if ((PHP_OS == "Linux") and !isset($hostname)) {
                                // copy the file to a semi-permanent location
            if (! $basedir = make_upload_directory("$course->id")) {
                error("The site administrator needs to fix the file permissions for the data directory");
            }
                if (!isset($hostname_access_error)) {
              $bname=basename($filename);
            $cleanfilename = clean_filename($bname);
            if ($cleanfilename) {
                $newfile = "$basedir/$cleanfilename";
                if (move_uploaded_file($filename, $newfile)) {
                    chmod($newfile, 0666);
                    clam_log_upload($newfile,$course);
                } else {
                    notify(get_string("uploadproblem", "", $filename));
                }
            }
            $filename = $newfile;
                }
            print_heading_with_help($strimportquestions, "import", "quiz");
            print_simple_box_start("center");
                if ($hostname_access_error) { notify("couldn't connect to ODBC Socket Server on " . $hostname_access_error); }
            echo "<form method=\"post\" action=\"import.php\">";
            echo "<table cellpadding=\"5\">";

        echo "<tr><td align=\"right\">";
            echo "What is the hostname or IP address of the ODBC Socket Server:</td><td>";
            echo " <input name=\"hostname\" type=\"text\" size=\"50\" value=\"".stripslashes($hostname_access_error)."\" />";
            echo " <input name=\"filename\" type=\"hidden\" value=\"".$filename."\" />";
            echo " <input name=\"category\" type=\"hidden\" value=\"".$category->id."\" />";
            echo " <input name=\"format\" type=\"hidden\" value=\"".$form->format."\" />";
            echo "</td><td>&nbsp;</td></tr>";
        echo "<tr><td align=\"right\">";
            echo "What is the location of the database (.mdb file) on the Socket Server:</td><td>";
            echo " <input name=\"mdbpath\" type=\"text\" size=\"50\" value=\"".stripslashes($mdbpath)."\" />";
                echo "</td><td>&nbsp;</td></tr>";
        echo "<tr><td align=\"right\">";
            echo "What is the location of the system database (System.mda file) on the Socket Server:</td><td>";
            echo " <input name=\"mdapath\" type=\"text\" size=\"50\" value=\"".stripslashes($mdapath)."\" />";
                echo "</td><td>&nbsp;</td></tr>";
            echo "<tr><td>&nbsp;</td><td>";
            echo " <input type=\"submit\" name=\"save\" value=\"Connect to Server\" />";
            echo "</td></tr>";
            echo "</table>";
            echo "</form>";
            print_simple_box_end();
            print_footer($course);
          exit;
            }

            // we get here if running windows or after connect to ODBC socket server on linux
//
// this generates the page to choose categories of questions to import
//
        if (!isset($question_category)) {

                if (PHP_OS == "WINNT") {
                    // copy the file to a semi-permanent location
                if (! $basedir = make_upload_directory("$course->id")) {
                    error("The site administrator needs to fix the file permissions for the data directory");
                }
              $bname=basename($filename);
            $cleanfilename = clean_filename($bname);
            if ($cleanfilename) {
                $newfile = "$basedir/$cleanfilename";
                if (move_uploaded_file($filename, $newfile)) {
                    chmod($newfile, 0666);
                    clam_log_upload($newfile,$course);
                } else {
                    notify(get_string("uploadproblem", "", $filename));
                }
            }
            $filename = $newfile;
                }
        // end of file copy

                // don't have to do this on linux, since it's alreay been done in the test above
        if (PHP_OS == "WINNT") { $question_categories = $this->getquestioncategories($filename); }
        // print the intermediary form
            if (!$categories = question_category_menu($course->id, true)) {
                error("No categories!");
            }
            print_heading_with_help($strimportquestions, "import", "quiz");
            print_simple_box_start("center");
            echo "<form method=\"post\" action=\"import.php\">";
            echo "<table cellpadding=\"5\">";
        echo "<tr><td align=\"right\">";
            echo "Choose a category of questions to import:</td><td>";
            asort($question_categories);
            choose_from_menu($question_categories, "question_category","All Categories","All Categories", "", "allcategories");
            echo " <input name=\"filename\" type=\"hidden\" value=\"".$filename."\" />";
            echo " <input name=\"category\" type=\"hidden\" value=\"".$category->id."\" />";
            echo " <input name=\"format\" type=\"hidden\" value=\"".$form->format."\" />";
            if (PHP_OS == "Linux") {
                echo " <input name=\"hostname\" type=\"hidden\" value=\"".stripslashes(trim($hostname))."\" />";
                echo " <input name=\"mdbpath\" type=\"hidden\" value=\"".stripslashes($mdbpath)."\" />";
                echo " <input name=\"mdapath\" type=\"hidden\" value=\"".stripslashes($mdapath)."\" />";
            }
            echo "</td><td>&nbsp;</td>";
            echo "</tr><tr><td>&nbsp;</td><td>";
            echo " <input type=\"submit\" name=\"save\" value=\"Import Questions\" />";
            echo "</td></tr>";
            echo "</table>";
            echo "</form>";
            print_simple_box_end();
            print_footer($course);
          exit;
        }
//
// this is the main import section
//
    notify("Importing questions");
    if (PHP_OS == "Linux") {
        $hostname = trim($hostname);
        $records = $this->getquestions($mdbpath,$question_category,$mdapath, $hostname);
    } else {
        $records = $this->getquestions($filename,$question_category);
    }
                foreach ($records as $qrec)
                {
                    $question = $this->defaultquestion();
                    if ($qrec[9] != "") {
                        $question->image = $qrec[9];
                    }
//  0   Selected
//  1   PracticeTestOK?
//  2   QuestionText
//  3   QuestionType
//  4   Option1Text
//  5   Option2Text
//  6   Option3Text
//  7   Option4Text
//  8   CorrectAnswer
//  9   Graphic
//  10  Module
//  11  ChapterNumber
//  12  PageNumber
          $ref = "Answer can be found in chapter ". $qrec[11] . ", page " . $qrec[12] . ".";
                    switch ($qrec[3]) {
                  case 1:
                    $question->qtype = MULTICHOICE; // MULTICHOICE, SHORTANSWER, TRUEFALSE
        //          echo "<pre>";echo htmlspecialchars($qrec[2]); echo "</pre>";
                    $question->questiontext = addslashes(trim($qrec[2]));
        //          echo "<pre>";echo $question->questiontext; echo "</pre>";
                    $question->name = preg_replace("/<br />/", "", $question->questiontext);
                    $question->single = 1;  // Only one answer is allowed -- used for multiple choicers
                            $fractionset = 0;
                            for ($i=4;$i<=7;$i++) {
                                if ($qrec[$i] != "") {
                                    $question->answer[$i-3]=addslashes($qrec[$i]);
                                    if ($qrec[8] == $i-3) {  // if this is the index of CorrectAnswer
                                      $question->fraction[$i-3] = 1;
                                      $fractionset = 1;
                                    } else {
                                      $question->fraction[$i-3] = 0;
                                    }
                                    $question->feedback[$i-3] = (($qrec[8] == $i-3)?"Correct. ":"Incorrect. ") . $ref;
                                }
                            }
                            if ($fractionset == 0) { $question->fraction[1] = 1; }
                        break;
                        case 2:  // TRUE FALSE
                    $question->qtype = TRUEFALSE;
                    $question->questiontext = addslashes(trim($qrec[2]));
                    $question->name = preg_replace("/<br />/", "", $question->questiontext);
                            // for TF, $question->answer should be 1 for true, 0 for false
                    if ($qrec[8] == "T") { $question->answer =1;} else { $question->answer = 0; }
                      // for TF, use $question->feedbacktrue and feedbackfalse
                    $question->feedbacktrue = (($qrec[8] =="T")?"Correct. ":"Incorrect. ") . $ref;
                    $question->feedbackfalse = (($qrec[8] =="F")?"Correct. ":"Incorrect. ") . $ref;
                        break;
                        case 3:
                    $question->qtype = SHORTANSWER;
                    $question->questiontext = addslashes(trim($qrec[2]));
        //          echo "<pre>";echo $question->questiontext; echo "</pre>";
                    $question->name = preg_replace("/<br />/", "", $question->questiontext);
                    $question->usecase=0;  // Ignore case -- for SHORT ANSWER questions
                            $answers = explode("~", $qrec[8]);
                            $question->answer[0]=" ";
                            $question->fraction[0]=1;
                            for ($i=0;$i<count($answers);$i++) {
                                $question->answer[$i] = addslashes(trim($answers[$i]));
                                $question->feedback[$i] = $ref;
                                $question->fraction[$i] = 1; // 1 for 100%, 0 for none or somewhere in between
                            }
                        break;
                        case 4:
                          $question = 0;
                            notify("Cannot use essay questions - skipping question ". $qrec[2] . " " . $ref);
                        break;
                        default:
                            $question = 0;
                            notify("Misformatted Record.  Question Skipped.");
                        break;
                    }
          if ($question) { $questions[] = $question; }
                }
                $count = 0;
                // process all the questions
                if (PHP_OS == "WINNT") {
                    $filename = str_replace("\\\\","\\",$filename);
                    $filename = str_replace("/","\\",$filename);
                }
                foreach ($questions as $question) {   // Process and store each question
          $count++;
          echo "<hr /><p><b>$count</b>. ".stripslashes($question->questiontext)."</p>";
          $question->category = $this->category->id;
          $question->stamp = make_unique_id_code();  // Set the unique code (not to be changed)
          if (!$question->id = insert_record("question", $question)) {
              error("Could not insert new question!");
          }
          $this->questionids[] = $question->id;
          // Now to save all the answers and type-specific options
          $result = save_question_options($question);
          if (!empty($result->error)) {
              notify($result->error);
              $this->deletedatabase($filename);
              return false;
          }
          if (!empty($result->notice)) {
              notify($result->notice);
              $this->deletedatabase($filename);
              return true;
          }
            // Give the question a unique version stamp determined by question_hash()
            set_field('question', 'version', question_hash($question), 'id', $question->id);
        }
        $this->deletedatabase($filename);
        return true;
    }

    function importpostprocess() {
        return true;
    }

      function deletedatabase($filename) {
        if (! $this->fulldelete($filename)) {
        echo "<br />Error: Could not delete: $filename";
        return false;
      }
            return true;
      }

        function getquestions($filename, $category, $mdapath="", $hostname="") {
            if (($category == "allcategories") or ($category == "")) {
            $sql = "SELECT * FROM TBQuestions";
            } else {
            $sql = "SELECT * FROM TBQuestions where module = '".$category."'";
            }
            if (PHP_OS == "WINNT") {
            $ldb =& $this->connect_win($filename);
              $qset = $ldb->Execute("$sql");
          if ( $qset->RecordCount() > 0 ) {
            $records = $qset->GetAssoc(true);
              } else {
            $this->err("There were no records in the database.",$dsn);
              $ldb->Close();
              return false;
              }
            $ldb->Close();
            } else  { // if PHP_OS == WINNT
              // we have a linux installation
                $result = $this->query_linux($sql,$filename, $mdapath,$hostname);
          if ( count($result) > 0 ) {
                    // get rid of the ID field in the first column.
                    for($i=0;$i<count($result);$i++) {
                        foreach (array_keys($result[$i]) as $j) {
                            $records[$i][$j-1] = $result[$i][$j];
                        }
                    }
              } else {
            $this->err("There were no records in the database.",$dsn);
                    $ldb->Close();
              return false;
              }
                // xml test and connect
            }  // PHP_OS TEST
            return $records;
        }

    function getquestioncategories($filename, $mdapath="", $hostname="") {
      global $CFG, $result;
            $sql = "SELECT Distinct module FROM TBQuestions";
            if (PHP_OS == "WINNT") {
                $ldb =& $this->connect_win($filename);
                $qset = $ldb->Execute("$sql");
        if ( $qset->RecordCount() > 0 ) {
          $records = $qset->GetArray(true);
                  foreach ($records as $record) {
                    $categories[$record[0]] = $record[0];
                  }
          } else { // if recordcount
          $this->err("There were no records in the database.",$dsn);
                $ldb->Close();
            return false;
          }
        $ldb->Close();
            } else  { // if PHP_OS == WINNT
              // we have a linux installation
                    $result = $this->query_linux($sql, $filename, $mdapath, $hostname);
                    for($i=0;$i<count($result);$i++) {
                        $categories[$result[$i][0]] = $result[$i][0];
                    }
            }  // PHP_OS TEST
            return $categories;
    }

        function query_linux($sql, $mdbpath, $mdapath, $hostname) {
                global $result;
                include_once("odbcsocketserver.class.php");
                // set up socket server object to connect to remote host
                $oTest = new ODBCSocketServer;
                //Set the Hostname, port, and connection string
              $oTest->sHostName = $hostname;
                $oTest->nPort = 9628;
//            $oTest->sConnectionString="DRIVER=Microsoft Access Driver (*.mdb);SystemDB=C:\CTM\System.mda;DBQ=C:\CTM\of2K3\ctm.mdb;UID=Assess;PWD=VBMango;";
              $oTest->sConnectionString="DRIVER=Microsoft Access Driver (*.mdb);SystemDB=".
                $mdapath.";DBQ=".$mdbpath.";UID=Assess;PWD=VBMango;";
                // send and receive XML communication
                $qResult = $oTest->ExecSQL($sql);
                // set up XML parser to read the results
                $xml_parser = xml_parser_create("US-ASCII");
                xml_set_element_handler($xml_parser, "quiz_xmlstart", "quiz_xmlend");
        xml_set_character_data_handler($xml_parser, "quiz_xmldata");
        // parse the XML and get back the result set array
        if (!xml_parse($xml_parser, $qResult)) {
            $this->err("XML error: ".xml_error_string(xml_get_error_code($xml_parser))
              ." at line ".xml_get_current_line_number($xml_parser),$oTest->sConnectionString);
                    return false;
        } else  {
//          echo("Successful XML parse.  ");
            // prepare the array for use in the pull-down
/*          echo "<br />count of rows is ". count ($result);
                    echo "<pre>\n";
                    $qResult = HtmlSpecialChars($qResult);
                    echo $qResult;
                    echo "\n</pre>";
*/
                xml_parser_free($xml_parser);
//  $sResult = HtmlSpecialChars($qResult);
    //echo("<pre>");
//  echo($sResult);
//  echo("</pre>");

                    return $result;
        }
        }

        function connect_win($filename) {
            global $CFG, $systemdb;
            // first, verify the location of System.mda
            if (!isset($systemdb)) {
            $systemdb=$this->findfile("System.mda");
            }
        if (! $systemdb) {
        $this->err("The system database System.mda cannot be found.  Check that you've uploaded it to the course.",$dsn);
        die;
        }

            $ldb = &ADONewConnection('access');
          $dsn="DRIVER=Microsoft Access Driver (*.mdb);SystemDB=".$systemdb.";DBQ=".$filename.";UID=Assess;PWD=VBMango;";
          $dbconnected = $ldb->Connect($dsn);
        if (! $dbconnected) {
        $this->err("Moodle could not connect to the database.",$dsn);
        die;
        }
            return $ldb;
        }

    function err($message, $dsn) {
            echo "<font color=\"#990000\">";
          echo "<p>Error: $message</p>";
          echo "<p>ODBC File DSN: $dsn<br />";
          echo "</font>";
    }

        function fulldelete($location) {
            if (is_dir($location)) {
                $currdir = opendir($location);
                while ($file = readdir($currdir)) {
                    if ($file <> ".." && $file <> ".") {
                        $fullfile = $location."/".$file;
                        if (is_dir($fullfile)) {
                            if (!fulldelete($fullfile)) {
                                return false;
                            }
                        } else {
                            if (!unlink($fullfile)) {
                                return false;
                            }
                        }
                    }
                }
                closedir($currdir);
                if (! rmdir($location)) {
                    return false;
                }

            } else {
                if (!unlink($location)) {
                    return false;
                }
            }
            return true;
        }


    function findfile($filename) {
        global $CFG;
            $dirs = $this->getcoursedirs();
            $dirs[] = $CFG->dirroot."\mod\quiz\format";
            foreach ($dirs as $dir) {
                $file = $dir . "\System.mda";
                // look for System.mda
                if (is_file($file)) return $file;
            }
            return false;
    }

    function getcoursedirs() {
        global $CFG;
        // for every course in the system, find the root of the data directory
                $courses = get_records_sql("select distinct id,fullname from ".$CFG->prefix."course");
                $dirs = array();
                if ($courses) {
                    foreach ($courses as $course) {
                        $dir = $CFG->dataroot . "/" . $course->id;
                        if (is_dir($dir)) { $dirs[] = $dir; }
                    }
                }
                return $dirs;
    }

} // END OF CLASS

    //Handler for starting elements
    function quiz_xmlstart($parser, $name, $attribs) {
        global $result,$row, $col, $incolumn;
        $name = strtolower($name);
        switch ($name) {
            case "row":
        $col=0;break;
            case "column":
                $incolumn = 1;break;
            case "error":
        break;
            case "result":
                $row = 0; break;
        } // switch
    }

    //handler for the end of elements
    function quiz_xmlend($parser, $name) {
        global $result, $row, $col, $incolumn;
        $name = strtolower($name);
        switch ($name) {
            case "row":
        $row++;break;
            case "column":
                $incolumn = 0;
        $col++;
        break;
            case "error":
        break;
            case "result":
        break;
        } // switch
    }  // function

    //handler for character data
    function quiz_xmldata($parser, $data) {
        global $result, $row, $col, $incolumn;
        if ($incolumn) { $result[$row][$col] = $result[$row][$col] . $data;
        }
    }

?>