<?php

/**
*	
*
* Version Moodle 1.9 : Georges Khaznadar
*
* Update Moodle 2.2 : ROY Emile (update functions to match moodle 2.2)
* 
*/


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 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);
    }
}


