This file is indexed.

/usr/share/moodle/mod/assignment/type/wims/assignment.class.php is in wims-moodle 4.0-18.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
<?php

/**
*	Version moodle 2.2 emile.roy@univ-mlv.fr
*
*
*Based on Georges Khaznadar developements
*
*/


require_once($CFG->libdir.'/formslib.php');
require_once($CFG->libdir . '/portfoliolib.php');
require_once($CFG->dirroot . '/mod/assignment/lib.php');
require_once($CFG->libdir . '/filelib.php');
require_once("wimsclass.php");
require_once("wims_raw.php");
 require_once("wimsconf.php");    
/**
 * Wims class (create a link between moodle and wims)
 *
 */
class assignment_wims extends assignment_base {

    var $filearea = 'submission';

    function assignment_wims($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
        parent::assignment_base($cmid, $assignment, $cm, $course);
        $this->type = 'wims';
	$this->wimsClassId=$this->createWimsClass();
    }

    
    function createWimsClass(){
	global $DB, $CFG;
	if(is_object($this->cm)){
	if ($this->cm->id){
   	if (! $this->assignment->var2 || intval($this->assignment->var2) <= 0){
	// the wims virtual class does not yet exist.

	$wc=new wc_data($this->assignment,
			$CFG->protocol,
			$CFG->passwims);
	$this->initJobRaw();
	// at this point, a request is sent to the wims server
	// if $_GETS['retry'] == '1', that means that such a request has
	// been sent already; otherwise it is the first attempt.
	$lines=$this->jr->addclass($wc,$wc->description);
	if ($this->jr->ok){
		
	  // at this point, a class has been created by WIMS successfully;
	  // however the job addclass is not supposed to return the code of
	  // the created class. So we must get it now.
	  $this->assignment->var2=intval($lines[1]);
	 // update_record("assignment",$this->assignment);
	    $DB->update_record("assignment",$this->assignment);
} else { // the class has not been added !!
	  $this->assignment->var2="-1";
	//  update_record("assignment",$this->assignment);
 $DB->update_record("assignment",$this->assignment);
	}
      }
    } 
    return $this->assignment->var2;
  }
}


function reTryButton(){
    $result="<form><input type='hidden' name='retry' value='1' /><input type='hidden' name='id' value='%s' /><input type='submit' value='%s'/>&nbsp;%s</form>";
    $result=sprintf($result,$this->cm->id,
            get_string("retry","assignment_wims"),
            get_string("maybewimsbusy","assignment_wims"));
    return $result;
  }


  function initJobRaw(){
    global $CFG;
    $this->jr=new job_raw($CFG->wimshost,
			  $CFG->wimsroot,
			  $CFG->protocol,
			  $CFG->passwims);
    return $this->jr;
  }


  /**
   * returns the status of the user: True if she is a teacher.
   */
  function isTeacher(){
    global $USER;
 	$context = get_context_instance(CONTEXT_MODULE, $this->cm->id);

    return has_capability('mod/assignment:grade',$context);
	
}

 /**
   * Displays a button to enter the Wims miniclass
   * if the user does not exist yet in the miniclass, she is
   * created on the fly.
   */
  function miniClassEnterButton(){
    global $USER;
     global $CFG;
	
    if ($this->isTeacher()){
      $login="supervisor";
      $prompt=get_string("adminsheet","assignment_wims");


    } else {
      $prompt=get_string("apply","assignment_wims");

      $this->ensureUserExists();
      $login=$USER->username;
    }
    $lines=$this->jr->authuser($this->assignment->var2,
			       rclass($this->assignment),
			       $login);
    $this->getSession($login);
    if ($this->session){
      $result=$this->wimsButton($prompt,array("session"=>"$this->session","lang"=>$this->wimsLang()));
    } else {
      $result=get_string("sorrynoauthuser","assignment_wims");
    }
    return $result;
  }

 /**
   * Returns the links for the wims class
   * @param var1 integer, defaults to 0
   * if $this->assignment->var1 is 0, it is an ordinary worksheet
   * if $this->assignment->var1 is 1, it is an exam.
   */
  function wims_links(){
    $this->initJobRaw();

	
    if ($this->assignment->var1==0){
      return $this->miniClassEnterButton() .
	$this->miniClassSheetFeedback().
	$this->miniClassGradesOrAdmin();
    } else {
      return $this->miniClassEnterButton() .
	$this->miniClassExamFeedback() .
	$this->importableSheets();
    }
  }

    function view() {
        global $OUTPUT, $CFG, $USER, $PAGE;

        $edit  = optional_param('edit', 0, PARAM_BOOL);
        $saved = optional_param('saved', 0, PARAM_BOOL);

        $context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
        require_capability('mod/assignment:view', $context);

        $submission = $this->get_submission($USER->id, false);

        //Guest can not submit nor edit an assignment (bug: 4604)
        if (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
            $editable = false;
        } else {
            $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
        }
        $editmode = ($editable and $edit);

        if ($editmode) {
            // prepare form and process submitted data
            $editoroptions = array(
                'noclean'  => false,
                'maxfiles' => EDITOR_UNLIMITED_FILES,
                'maxbytes' => $this->course->maxbytes,
                'context'  => $this->context
            );

            $data = new stdClass();
            $data->id         = $this->cm->id;
            $data->edit       = 1;
            if ($submission) {
                $data->sid        = $submission->id;
                $data->text       = $submission->data1;
                $data->textformat = $submission->data2;
            } else {
                $data->sid        = NULL;
                $data->text       = '';
                $data->textformat = NULL;
            }

            $data = file_prepare_standard_editor($data, 'text', $editoroptions, $this->context, 'mod_assignment', $this->filearea, $data->sid);

            $mform = new mod_assignment_wims_edit_form(null, array($data, $editoroptions));

            if ($mform->is_cancelled()) {
                redirect($PAGE->url);
            }

            if ($data = $mform->get_data()) {
                $submission = $this->get_submission($USER->id, true); //create the submission if needed & its id

                $data = file_postupdate_standard_editor($data, 'text', $editoroptions, $this->context, 'mod_assignment', $this->filearea, $submission->id);

                $submission = $this->update_submission($data);

                //TODO fix log actions - needs db upgrade
                add_to_log($this->course->id, 'assignment', 'upload', 'view.php?a='.$this->assignment->id, $this->assignment->id, $this->cm->id);
                $this->email_teachers($submission);

                //redirect to get updated submission date and word count
                redirect(new moodle_url($PAGE->url, array('saved'=>1)));
            }
        }

        add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", $this->assignment->id, $this->cm->id);

/// print header, etc. and display form if needed
        if ($editmode) {
            $this->view_header(get_string('editmysubmission', 'assignment'));
        } else {
            $this->view_header();
        }

        $this->view_intro();

        $this->view_dates();

   if (has_capability('mod/assignment:submit', $context) ||
	has_capability('mod/assignment:grade', $context)) {
     


echo $OUTPUT->box_start('generalbox boxwidthwide boxaligncenter', 'wims');

	

      if ($this->wimsClassId > 0){
	// A wims class exists. Let us decribe it and make a link for it
	if ($this->isTeacher()||$this->isopen()){
	  // the links for the class will always be visible for a teacher
	  print $this->wims_links();
	} else {
	  print(get_string("sorrynotopen","assignment_wims"));
	}
      } else {
	print(get_string("sorrynothing","assignment_wims"));
	print($this->reTryButton());
      }
    echo $OUTPUT->box_end();
      
    }

        $this->view_feedback();

        $this->view_footer();
    }


  /**
   * Ensures that the user $USER exists in the Wims miniclass
   */
  function ensureUserExists(){
    global $USER;
    $login=$USER->username;
    $lines=$this->jr->getuser($this->assignment->var2,
			      rclass($this->assignment),$login);
	


$tmp = $lines[1];



 if (!$this->jr->ok and $lines[1]=="bad user (empty quser or bad chars detected)"){
	
 $firstname=wimsIconv($USER->firstname);
      $lastname=wimsIconv($USER->lastname);

      $lines=$this->jr->adduser($this->assignment->var2,
				rclass($this->assignment),
				$firstname,$lastname,$login);
    }
  } 

  /**
   * defines $this->$session with the name of an authenticated session 
   * for user $login in the Wims miniclass
   */
  function getSession($login){
    $lines=$this->jr->authuser($this->assignment->var2,
			       rclass($this->assignment),
			       $login);
    if ($this->jr->ok) {
      $this->session=$lines[1];
    } else {
      $this->session="";
    }
  }

  function wimsButton($prompt,$dict){
    global $CFG;
 global $USER;
    $backurl=$CFG->wwwroot."/mod/assignment/view.php?id=".$this->cm->id;
    $closemsg=wimsIconv(get_string("closeandupdate","assignment_wims"));
    $url=$CFG->wimsRemoteUrl."/".$CFG->wimsroot."/wims.cgi?";
    $amp="";
    foreach($dict as $k=>$v){
      $url.=$amp."$k=$v";
      $amp="&";
    }
    $tfurl=$CFG->wwwroot."/mod/assignment/type/wims/twoframes.php?url=".urlencode($url)."&backurl=".urlencode($backurl)."&closemsg=".urlencode($closemsg);
    $result="<div class='navbutton'>\n".
      "<form>\n<input type='button' value='$prompt' onclick='window.open(\"$tfurl\",\"wims_win\",\"toolbar=no,menubar=no,personalbar=no\")'>\n</form>\n</div>\n";
    return $result;
  }

  /**
   * returns the lang for the Wims miniclass
   */
  function wimsLang(){
	global $USER;

   $lang=$USER->lang;


    if (strlen($lang) == 0) $lang="en";
	
    return substr($lang,0,2);

  }

/**
   * displays a column of buttons to enter directly existing worksheets
   * if there is no worksheet, gives a hint about their future creation
   * for the supervisor, gives also links to get the sheet's contents
   */
  function miniClassSheetFeedback(){
    $result="";
    $lines=$this->jr->getcsv($this->assignment->var2,
			     rclass($this->assignment),
			     "sheets");
    $this->meansheet=0;
    if ($this->jr->ok){
      $sheets=explode(",",$lines[0]);
      if ($sheets[0] != "ERROR"){
	$sheetnames=explode(",",$lines[1]);
	$i=0;
	$this->totalsheet=0;
	$this->countsheet=0;
	$result.="<div class='feedback'><div class='fullname'>".get_string("listofsheets","assignment_wims")."</div>\n";
	$result.="<table>\n";
	foreach($sheets as $s) {
	  $sn=$sheetnames[$i];
	  $i++; $si="".$i;
	  $result.=$this->miniClassSheetFeedbackLine($sn,$si);
	}
      } else {
	$result.=$this->hintNewSheet();
      }
      $result.="</table></div>\n";
	if (isset($this->countsheet) && $this->countsheet!=0){

      $this->meansheet=$this->totalsheet/$this->countsheet;}else{
	$this->meansheet = 0;
}

    }
    return $result;
  }
/**
   * displays one button to enter directly an existing worksheet
   * for the supervisor, gives also links to get the sheet's contents
   */
  function miniClassSheetFeedbackLine($sn,$si){
    global $CFG,$USER;
    $result=" <tr><td>";
    if($this->isTeacher()){
      $result.=$this->wimsButton(wimsIconv($sn,"back"),array("session"=>"$this->session","lang"=>$this->wimsLang(),"module"=>"adm/class/sheet","sheet"=>"$si"));

      $result.="</td><td>";
      $url=urlencode($this->jr->url("getclassfile",
				    "qclass=".$this->assignment->var2.
				    "&rclass=".urlencode(rclass($this->assignment)).
				    "&option=sheets/.sheet".$si
				    ));
      $result.="<a href='".$CFG->wwwroot."/mod/assignment/type/wims/getsheetsource.php?url=$url' target='_new'>".
	get_string("getsheetsource","assignment_wims").
	"</a>";
      // get the CSV of the scores.
      $url=urlencode($this->jr->url("getcsv",
				    "qclass=".$this->assignment->var2.
				    "&rclass=".urlencode(rclass($this->assignment)).
				    "&option=lastname,name,sheet$si"
				    ));	      
      $result.="&nbsp;</td><td>&nbsp;<a href='".$CFG->wwwroot."/mod/assignment/type/wims/getcsv.php?url=$url' target='_new'>".
	get_string("getcsv","assignment_wims").
	"&nbsp;($si)</a>";
    } else {
      $result.=$this->wimsButton(wimsIconv($sn,"back"),array("session"=>"$this->session","lang"=>$this->wimsLang(),"module"=>"adm/sheet","sh"=>"$si"));

      $result.="</td><td>";
      $login=$USER->username;
      $lines1=$this->jr->getscore($this->assignment->var2,
				  rclass($this->assignment),
				  $login,
				  $si);
      if ($this->jr->ok){
	$avg=array();
	$weight=array();
	$readAvg=0;
	$readWeight=0;
	foreach($lines1 as $l){
	  if(substr($l,0,14)=="scoreaverages="){
	    $avg=explode(" ",substr($l,14,1024)); 
	    // got the first line of averages
	    // but this not necessary the relevant line
	    // so take in account the number $si
	    if ($si>1) $readAvg=$si;
	  }else{
	    if ($readAvg>0){
	      $readAvg-=1;
	      if ($readAvg==1){
		// we read $si lines, this is the good one to take in account
		$avg=explode(" ",$l);
		$readAvg=0;
	      }
	    }
	  }
	  if(substr($l,0,8)=="weights="){
	    $weight=explode(" ",substr($l,8,1024));
	    // got the first line of weights
	    // but this not necessary the relevant line
	    // so take in account the number $si
	    if ($si>1) $readWeight=$si;
	  }else{
	    if ($readWeight>0){
	      $readWeight-=1;
	      if ($readWeight==1){
		// we read $si lines, this is the good one to take in account
		$weight=explode(" ",$l);
		$readWeight=0;
	      }
	    }
	  }
	}
	$total=0;
	$max=0;
	$i=0;
	foreach($weight as $w){
	  // we should get rid of elements containing "\\"
	  if ($w!="\\"){
	    $max+=$w;
	    $total+=$avg[$i]*$w;
	    $i++;
	  }
	}
	$score=$total/$max;
	//now $score is a mark in a scale ranging fro 0 to 10
	$score*=$this->assignment->grade/10;
	//now $score is a mark in a scale ranging 
	//from 0 to =$this->assignment->grade
      } else {
	$score=-1000; // we should trigger an error message!
      }
      $this->countsheet+=1;
      $this->totalsheet+=$score;
      $result.=get_string("score_is","assignment_wims").$this->roundedGrade($score)."</td>";
    }
    $result.="</tr>\n";
    return $result;
  }

/**
   * Displays a rounded grade with the maximum visible
   */
  function roundedGrade($grade){
    return (round(100*$grade)/100)."&nbsp;/&nbsp;".$this->assignment->grade;
  }



 /**
   * Displays the grades and updates them in Moodle for a student
   * Adds a button to enter the miniclass in admin mode for the teacher
   */
  function miniClassGradesOrAdmin(){
    global $USER;
global $DB;    
global $CGF;
$result="";
    if (!$this->isTeacher()){ // it's a student
      $result.=get_string("meansheet","assignment_wims")."&nbsp;".$this->roundedGrade($this->meansheet)."<br />\n";
      //if($sub=get_record("assignment_submissions","assignment",$this->assignment->id,"userid",$USER->id)){
if($sub=$DB->get_record("assignment_submissions",array("assignment"=>$this->assignment->id,"userid"=>$USER->id))){
		
if($this->meansheet != round($sub->grade)){
	  $sub->grade=round($this->meansheet);
	  $sub->timemodified=time();
	  $sub->timemarked=time();
	  $sub->submissioncomment=get_string("automatic_score","assignment_wims");
	  $DB->update_record("assignment_submissions",$sub);
	}
      } else {
	$sub=$this->prepare_new_submission($USER->id);
	$sub->grade=round($this->meansheet);
	$sub->timemarked=time();
	$sub->submissioncomment=get_string("automatic_score","assignment_wims");
	$id=$DB->insert_record("assignment_submissions",$sub);
      }
    } else { // it's a teacher
      $result.=$this->wimsButton(get_string("adminclass","assignment_wims"),array('session'=>$this->session,'lang'=>$this->wimsLang(),'module'=>'adm/class/config'));
    }
    return $result;
  }

  /**
   * makes easier the importation of wims sheets published in the past
   */
  function importableSheets(){
    global $CFG;
global $DB;
    if (! $this->isTeacher()) return "";
    // display importable sheets only for the teachers.
    $course= $DB->get_record("course", array("id"=>$this->cm->course));
    //require_course_login($course); error moodle 2
	require_login(); 
	
    // make up a list of our own Wims worksheets
    $ownsheets=$this->mySheets();
    $ownMD5sums=array();
    foreach($ownsheets as $ownsh){
      $ownMD5sums[]=md5($ownsh->contents($this->jr));
    }
    if (!$cms = get_coursemodules_in_course('assignment', $course->id, 'm.assignmenttype, m.timeavailable, m.var1,m.var2')) {
        notice(get_string('noassignments', 'assignment'), "../../course/view.php?id=$course->id");
        die;
    }
    // now $cms contains all assignments for this course.
    $result="<form method='post' action='?id=".$this->cm->id."'><table>\n";
    foreach ($cms as $c){
      if ($c->assignmenttype=="wims" && 
	  $c->timeavailable < $this->assignment->timeavailable &&
	  $c->var1==0){
	// we select assignments of type wims + ordinary worksheet
	// which have been made available *before* this exam.
	$sheets=$this->listSheets($c);
	if (count($sheets)>0){
	  $result.="<tr><th colspan='2'>".$c->name."</th></tr>\n";
	  foreach($sheets as $sh){
	    $url=$sh->addsheetToUrl($this,$ownMD5sums);
	    // TODO: the sheets should be added with their respective titles
	    if ($url=="") {
	      $importLink=get_string("already_imported","assignment_wims");
	    } else {
	      $importLink="<input type='checkbox' value='$url' name='imports[]' />&nbsp;".get_string("add_this_sheet","assignment_wims");
	    }
	    $result.="<tr><td>".$sh->title." :</td><td> $importLink</td></tr>\n";
	  }
	  $result.="</table>\n";
	  $result.="<input type='submit' value='".get_string("import_selected_sheets","assignment_wims")."' />";
	  $result.="<form>\n";
	}
      }
    }
    return "<h3>".get_string("importableSheets","assignment_wims")."</h3>\n".$result;
  }


  /**
   * lists the wims sheets contained in a course module
   * @return a table of quintuples (index,title, status, rclass, qclass)
   * @param cm a course module object, which must be augmented
   * with a member var2 which musr contain the value of the qclass
   */
  function listSheets($cm){
    $this->initJobRaw();
    $qclass=$cm->var2; 
    $rclass=rclassFromCourseAndModule($this->course,$cm);
    $lines=$this->jr->listsheets($qclass,$rclass);
    $result=array();
    if ($this->jr->ok){
      foreach ($lines as $l){
	if(substr($l,0,6)=="count="){
	  $count=1*substr($l,6,255);
	}
	if(substr($l,0,10)=="titlelist="){
	  $titlelist="x".substr($l,10,2048);
	  $titlelist=explode(":",$titlelist);
	}
      }
      for($i=0;$i<$count;$i++){
	$index=1*substr($titlelist[2*$i],1,255);
	$title=$titlelist[2*$i+1];
	$status=1*substr($titlelist[2*$i+2],0,1);
	$ws = new workSheet($index,$title,$status,$rclass,$qclass);
	$result[]=$ws;
      }
    }
    return $result;
  }


  /**
   * returns the sheets owned by this assignment of type wims
   */
  function mySheets(){
    $this->cm->var2=$this->assignment->var2; // copies the value of qclass
    return $this->listSheets($this->cm);
  }
  function hintNewSheet(){
    if ($this->isTeacher()){
	$result=get_string("makeasheet","assignment_wims");
      } else {
	$result=get_string("nosheetsyet","assignment_wims");
      }
    return $result;
  }
  /**
   * @return a list of exams
   */
  function exams(){
    $result=array();
    $lines=$this->jr->getcsv($this->assignment->var2,
			     rclass($this->assignment),
			     "exams");
    if($lines[0]=="ERROR") {
      return $result;
    } else {
      $titles=$lines[1];
      $l=strlen($titles);
      $titles=substr($titles,1,$l-2);
      $titles=explode('","',$titles);
      $indices=explode(",",$lines[0]);
      $qclass=$this->assignment->var2;
      $rclass=rclassFromCourseAndModule($this->course,$this->cm);
      for($i=0; $i<count($indices); $i++){
	$we= new wimsExam($indices[$i],$titles[$i],$rclass,$qclass);
	$result[]=$we;
      }
    }
    return $result;
  }

/**
   * gives a feedback for the exam
   */
  function miniClassExamFeedback(){
    global $USER,$CFG,$DB;
    $feedback="";
    $total=0;
    $n=0;
    if($exams=$this->exams()){
      $feedback.="<table>\n";
      foreach ($exams as $e){
	if($this->isTeacher()){
	  $feedback.="<tr><td>";
	  $feedback.=$this->wimsButton($e->title,array("session"=>"$this->session","lang"=>$this->wimsLang(),"module"=>"adm/class/exam","exam"=>$e->i));
	  $feedback.="</td><td>";
	  $url=urlencode($this->jr->url("getclassfile",
					"qclass=".$e->qclass.
					"&rclass=".$e->rclassEnc.
					"&option=exams/.exam".$e->i
				    ));
	  $feedback.="<a href='".$CFG->wwwroot."/mod/assignment/type/wims/getsheetsource.php?url=$url' target='_new'>".
	    get_string("getexamsource","assignment_wims").
	    "</a>";
	  $feedback.="</td></tr>\n";
	} else {
	  // TODO : create the buttons for a student !!!
	  $feedback.="<tr><td>";
	  $feedback.=$this->wimsButton($e->title,array("session"=>"$this->session","lang"=>$this->wimsLang(),"module"=>"adm/class/exam","job"=>"student","exam"=>$e->i));
	  $feedback.="</td><td>";
	  $login=$USER->username;
	  $lines1=$this->jr->getscore($e->qclass,$e->rclass,$login,$e->i);
	  $examBegin=-1;
	  foreach($lines1 as $l){
	    if(substr($l,0,11)=="examscores="){
	      $examBegin=0;
	      $l=substr($l,11,1024);
	      $scores=explode(" ",$l);
	    }
	    if($examBegin>=0){
	      if($l==""){
		$examBegin=-1;
	      } else {
		// take in account the sessions left
		if($examBegin==$e->i){
		  // it is the relevant line for this exam
		  $sessionData=explode(" ",$l);
		  $maxSession=1*$sessionData[0];
		  $doneSession=1*$sessionData[1];
		}
		$examBegin++;
	      }
	    }
	  }

	 $score=$scores[$e->i - 1]*$this->assignment->grade/10;
	  $total+=$score;
	  $n++;
	 
	  $feedback.=get_string("score_is","assignment_wims").$this->roundedGrade($score);
	  $feedback.="</td><td>";
	  $feedback.=" ... $doneSession/$maxSession ".get_string("sessions_done","assignment_wims");
	  $feedback.="</td></tr>";
	}
      }
      $feedback.="</table>";
      // now we shall submit the mean score if we are a student
      if (! $this->isTeacher()){
	$mean=$total/$n;
	$feedback.= get_string("exam_meanscore","assignment_wims")." ".$this->roundedGrade($mean)."<br />\n";
	if($sub=$DB->get_record("assignment_submissions",array("assignment"=>$this->assignment->id,"userid"=>$USER->id))){
	  if(round($mean) != $sub->grade){
	    $sub->grade=round($mean);
	    $sub->timemodified=time();
	    $sub->timemarked=time();
	    $sub->submissioncomment=get_string("automatic_score","assignment_wims");
	    $DB->update_record("assignment_submissions",$sub);
	  }
	} else {
	  $sub=$this->prepare_new_submission($USER->id);
	  $sub->grade=round($mean);
	  $sub->timemarked=time();
	  $sub->submissioncomment=get_string("automatic_score","assignment_wims");
	  $id=$DB->insert_record("assignment_submissions",$sub);
	}
      }
    } else {
      if($this->isTeacher()){
	$feedback=get_string("create_an_exam","assignment_wims");
	if (! $this->mySheets()){
	  $feedback.="<div class='noticebox notifyproblem'>".get_string("consider_imports","assignment_wims")."</div>";
	}
      } else {
	$feedback=get_string("no_exam_yet","assignment_wims");
      }
    }
    return "<h3>".get_string("examFeedback","assignment_wims")."</h3>\n$feedback";
  }


    /*
     * Display the assignment dates
     */
    function view_dates() {
        global $USER, $CFG, $OUTPUT;

        if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
            return;
        }

        echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
        echo '<table>';
        if ($this->assignment->timeavailable) {
            echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
            echo '    <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
        }
        if ($this->assignment->timedue) {
            echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
            echo '    <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
        }
        $submission = $this->get_submission($USER->id);
        if ($submission) {
            echo '<tr><td class="c0">'.get_string('lastedited').':</td>';
            echo '    <td class="c1">'.userdate($submission->timemodified);
        /// Decide what to count
            if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_WORDS) {
                echo ' ('.get_string('numwords', '', count_words(format_text($submission->data1, $submission->data2))).')</td></tr>';
            } else if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_LETTERS) {
                echo ' ('.get_string('numletters', '', count_letters(format_text($submission->data1, $submission->data2))).')</td></tr>';
            }
        }
        echo '</table>';
        echo $OUTPUT->box_end();
    }

    function update_submission($data) {
        global $CFG, $USER, $DB;

        $submission = $this->get_submission($USER->id, true);

        $update = new stdClass();
        $update->id           = $submission->id;
        $update->data1        = $data->text;
        $update->data2        = $data->textformat;
        $update->timemodified = time();

        $DB->update_record('assignment_submissions', $update);

        $submission = $this->get_submission($USER->id);
        $this->update_grade($submission);
        return $submission;
    }


    function print_student_answer($userid, $return=false){
        global $OUTPUT;
        if (!$submission = $this->get_submission($userid)) {
            return '';
        }

        $link = new moodle_url("/mod/assignment/type/wims/file.php?id={$this->cm->id}&userid={$submission->userid}");
        $action = new popup_action('click', $link, 'file'.$userid, array('height' => 450, 'width' => 580));
        $popup = $OUTPUT->action_link($link, shorten_text(trim(strip_tags(format_text($submission->data1,$submission->data2))), 15), $action, array('title'=>get_string('submission', 'assignment')));

        $output = '<div class="files">'./*.
                  '<img src="'.$OUTPUT->pix_url('f/html') . '" class="icon" alt="html" />'.
                  $popup .*/
                  '</div>';
                  return $output;
    }

    function print_user_files($userid, $return=false) {
        global $OUTPUT, $CFG;

        if (!$submission = $this->get_submission($userid)) {
            return '';
        }

        $link = new moodle_url("/mod/assignment/type/wims/file.php?id={$this->cm->id}&userid={$submission->userid}");
        $action = new popup_action('click', $link, 'file'.$userid, array('height' => 450, 'width' => 580));
        $popup = $OUTPUT->action_link($link, get_string('popupinnewwindow','assignment'), $action, array('title'=>get_string('submission', 'assignment')));

        $output = '<div class="files">'./*
                  '<img align="middle" src="'.$OUTPUT->pix_url('f/html') . '" height="16" width="16" alt="html" />'.
                  $popup .*/
                  '</div>';

        $wordcount = '<p id="wordcount">'. $popup . '&nbsp;';
    /// Decide what to count
        if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_WORDS) {
            $wordcount .= '('.get_string('numwords', '', count_words(format_text($submission->data1, $submission->data2))).')';
        } else if ($CFG->assignment_itemstocount == ASSIGNMENT_COUNT_LETTERS) {
            $wordcount .= '('.get_string('numletters', '', count_letters(format_text($submission->data1, $submission->data2))).')';
        }
        $wordcount .= '</p>';

        $text = file_rewrite_pluginfile_urls($submission->data1, 'pluginfile.php', $this->context->id, 'mod_assignment', $this->filearea, $submission->id);
        return $wordcount . format_text($text, $submission->data2, array('overflowdiv'=>true));


        }

    function preprocess_submission(&$submission) {
        if ($this->assignment->var1 && empty($submission->submissioncomment)) {  // comment inline
            if ($this->usehtmleditor) {
                // Convert to html, clean & copy student data to teacher
                $submission->submissioncomment = format_text($submission->data1, $submission->data2);
                $submission->format = FORMAT_HTML;
            } else {
                // Copy student data to teacher
                $submission->submissioncomment = $submission->data1;
                $submission->format = $submission->data2;
            }
        }
    }

    function setup_elements(&$mform) {
        global $CFG, $COURSE;
/* OLD CODE
        $ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));

        $mform->addElement('select', 'resubmit', get_string('allowresubmit', 'assignment'), $ynoptions);
        $mform->addHelpButton('resubmit', 'allowresubmit', 'assignment');
        $mform->setDefault('resubmit', 0);

        $mform->addElement('select', 'emailteachers', get_string('emailteachers', 'assignment'), $ynoptions);
        $mform->addHelpButton('emailteachers', 'emailteachers', 'assignment');
        $mform->setDefault('emailteachers', 0);

        $mform->addElement('select', 'var1', get_string('commentinline', 'assignment'), $ynoptions);
        $mform->addHelpButton('var1', 'commentinline', 'assignment');
        $mform->setDefault('var1', 0);
*/
    $wimsmode=array( 0 => get_string('defaultexercise', 'assignment_wims'), 1 => get_string('exam', 'assignment_wims'));
    
    $mform->addElement('select', 'var1', get_string('type_exe','assignment_wims'), $wimsmode);
    $mform->addHelpButton('var1','type_exe', 'assignment_wims');
    $mform->setDefault('var1', 0);


    }

    function portfolio_exportable() {
        return true;
    }

    function portfolio_load_data($caller) {
        $submission = $this->get_submission();
        $fs = get_file_storage();
        if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', $this->filearea, $submission->id, "timemodified", false)) {
            $caller->set('multifiles', $files);
        }
    }

    function portfolio_get_sha1($caller) {
        $submission = $this->get_submission();
        $textsha1 = sha1(format_text($submission->data1, $submission->data2));
        $filesha1 = '';
        try {
            $filesha1 = $caller->get_sha1_file();
        } catch (portfolio_caller_exception $e) {} // no files
        return sha1($textsha1 . $filesha1);
    }

    function portfolio_prepare_package($exporter, $user) {
        $submission = $this->get_submission($user->id);
        $options = portfolio_format_text_options();
        $html = format_text($submission->data1, $submission->data2, $options);
        $html = portfolio_rewrite_pluginfile_urls($html, $this->context->id, 'mod_assignment', $this->filearea, $submission->id, $exporter->get('format'));
        if (in_array($exporter->get('formatclass'), array(PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_RICHHTML))) {
            if ($files = $exporter->get('caller')->get('multifiles')) {
                foreach ($files as $f) {
                    $exporter->copy_existing_file($f);
                }
            }
            return $exporter->write_new_file($html, 'assignment.html', !empty($files));
        } else if ($exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
            $leapwriter = $exporter->get('format')->leap2a_writer();
            $entry = new portfolio_format_leap2a_entry('assignmentwims' . $this->assignment->id, $this->assignment->name, 'resource', $html);
            $entry->add_category('web', 'resource_type');
            $entry->published = $submission->timecreated;
            $entry->updated = $submission->timemodified;
            $entry->author = $user;
            $leapwriter->add_entry($entry);
            if ($files = $exporter->get('caller')->get('multifiles')) {
                $leapwriter->link_files($entry, $files, 'assignmentwims' . $this->assignment->id . 'file');
                foreach ($files as $f) {
                    $exporter->copy_existing_file($f);
                }
            }
            $exporter->write_new_file($leapwriter->to_xml(), $exporter->get('format')->manifest_name(), true);
        } else {
            debugging('invalid format class: ' . $exporter->get('formatclass'));
        }
    }

    function extend_settings_navigation($node) {
        global $PAGE, $CFG, $USER;

        // get users submission if there is one
        $submission = $this->get_submission();
        if (is_enrolled($PAGE->cm->context, $USER, 'mod/assignment:submit')) {
            $editable = $this->isopen() && (!$submission || $this->assignment->resubmit || !$submission->timemarked);
        } else {
            $editable = false;
        }

        // If the user has submitted something add a bit more stuff
        if ($submission) {
            // Add a view link to the settings nav
            $link = new moodle_url('/mod/assignment/view.php', array('id'=>$PAGE->cm->id));
            $node->add(get_string('viewmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);

            if (!empty($submission->timemodified)) {
                $submittednode = $node->add(get_string('submitted', 'assignment') . ' ' . userdate($submission->timemodified));
                $submittednode->text = preg_replace('#([^,])\s#', '$1&nbsp;', $submittednode->text);
                $submittednode->add_class('note');
                if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
                    $submittednode->add_class('early');
                } else {
                    $submittednode->add_class('late');
                }
            }
        }

        if (!$submission || $editable) {
            // If this assignment is editable once submitted add an edit link to the settings nav
            $link = new moodle_url('/mod/assignment/view.php', array('id'=>$PAGE->cm->id, 'edit'=>1, 'sesskey'=>sesskey()));
            $node->add(get_string('editmysubmission', 'assignment'), $link, navigation_node::TYPE_SETTING);
        }
    }

    public function send_file($filearea, $args) {
        global $USER;
        require_capability('mod/assignment:view', $this->context);

        $fullpath = "/{$this->context->id}/mod_assignment/$filearea/".implode('/', $args);

        $fs = get_file_storage();
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            send_file_not_found();
        }

        if (($USER->id != $file->get_userid()) && !has_capability('mod/assignment:grade', $this->context)) {
            send_file_not_found();
        }

        session_get_instance()->write_close(); // unlock session during fileserving
        send_stored_file($file, 60*60, 0, true);
    }

    /**
     * creates a zip of all assignment submissions and sends a zip to the browser
     */
    public function download_submissions() {
        global $CFG, $DB;

        raise_memory_limit(MEMORY_EXTRA);

        $submissions = $this->get_submissions('','');
        if (empty($submissions)) {
            print_error('errornosubmissions', 'assignment');
        }
        $filesforzipping = array();

        //NOTE: do not create any stuff in temp directories, we now support unicode file names and that would not work, sorry

        //online assignment can use html
        $filextn=".html";

        $groupmode = groups_get_activity_groupmode($this->cm);
        $groupid = 0;   // All users
        $groupname = '';
        if ($groupmode) {
            $groupid = groups_get_activity_group($this->cm, true);
            $groupname = groups_get_group_name($groupid).'-';
        }
        $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
                $submissioncontent = "<html><body>". format_text($submission->data1, $submission->data2). "</body></html>";      //fetched from database
                //get file name.html
                $fileforzipname =  clean_filename(fullname($a_user) . "_" .$a_userid.$filextn);
                $filesforzipping[$fileforzipname] = array($submissioncontent);
            }
        }      //end of foreach

        if ($zipfile = assignment_pack_files($filesforzipping)) {
            send_temp_file($zipfile, $filename); //send file and delete after sending.
        }
    }
}


  

class mod_assignment_wims_edit_form extends moodleform {
    function definition() {
        $mform = $this->_form;

        list($data, $editoroptions) = $this->_customdata;

        // visible elements
        $mform->addElement('editor', 'text_editor', get_string('submission', 'assignment'), null, $editoroptions);
        $mform->setType('text_editor', PARAM_RAW); // to be cleaned before display
        $mform->addRule('text_editor', get_string('required'), 'required', null, 'client');

        // hidden params
        $mform->addElement('hidden', 'id');
        $mform->setType('id', PARAM_INT);

        $mform->addElement('hidden', 'edit');
        $mform->setType('edit', PARAM_INT);

        // buttons
        $this->add_action_buttons();

        $this->set_data($data);
    }
}