File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.317.4.3: download - view: text, annotated - select for diffs
Thu Jan 6 22:38:11 2011 UTC (13 years, 4 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0_RC2, version_2_10_0
Diff to branchpoint 1.317: preferred, unified
- Backport 1.321.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Homework handler
    3: #
    4: # $Id: lonhomework.pm,v 1.317.4.3 2011/01/06 22:38:11 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: 
   28: 
   29: package Apache::lonhomework;
   30: use strict;
   31: use Apache::style();
   32: use Apache::lonxml();
   33: use Apache::lonnet;
   34: use Apache::lonplot();
   35: use Apache::inputtags();
   36: use Apache::structuretags();
   37: use Apache::randomlabel();
   38: use Apache::response();
   39: use Apache::hint();
   40: use Apache::outputtags();
   41: use Apache::caparesponse();
   42: use Apache::radiobuttonresponse();
   43: use Apache::optionresponse();
   44: use Apache::imageresponse();
   45: use Apache::essayresponse();
   46: use Apache::externalresponse();
   47: use Apache::rankresponse();
   48: use Apache::matchresponse();
   49: use Apache::chemresponse();
   50: use Apache::functionplotresponse();
   51: use Apache::drawimage();
   52: use Apache::Constants qw(:common);
   53: use Apache::loncommon();
   54: use Apache::lonlocal;
   55: use Time::HiRes qw( gettimeofday tv_interval );
   56: use HTML::Entities();
   57: use File::Copy();
   58: 
   59: # FIXME - improve commenting
   60: 
   61: 
   62: BEGIN {
   63:     &Apache::lonxml::register_insert();
   64: }
   65: 
   66: 
   67: =pod
   68: 
   69: =item set_bubble_lines()
   70: 
   71: Called at analysis time to set the bubble lines
   72: hash for the problem.. This should be called in the
   73: end_problemtype tag in analysis mode.
   74: 
   75: We fetch the hash of part id counters from lonxml
   76:     and push them into analyze:{part_id.bubble_lines}.
   77: 
   78: =cut
   79: 
   80: sub set_bubble_lines {
   81:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
   82: 
   83:     foreach my $key (keys(%bubble_counters)) {
   84: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
   85: 	    $bubble_counters{"$key"};
   86:     }
   87: }
   88: 
   89: #
   90: # Decides what targets to render for.
   91: # Implicit inputs:
   92: #   Various session environment variables:
   93: #      request.state -  published  - is a /res/ resource
   94: #                       uploaded   - is a /uploaded/ resource
   95: #                       contruct   - is a /priv/ resource
   96: #      form.grade_target - a form parameter requesting a specific target
   97: sub get_target {
   98:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
   99:     if( defined($env{'form.grade_target'})) {
  100: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
  101:     } else {
  102: 	&Apache::lonxml::debug("form.grade_target <undefined>");
  103:     }
  104:     if (($env{'request.state'} eq "published") ||
  105: 	($env{'request.state'} eq "uploaded")) {
  106: 	if ( defined($env{'form.grade_target'}  ) 
  107: 	     && ($env{'form.grade_target'} eq 'tex')) {
  108: 	    return ($env{'form.grade_target'});
  109: 	} elsif ( defined($env{'form.grade_target'}  ) 
  110: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
  111: 	    return ($env{'form.grade_target'});
  112: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
  113: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
  114: 	    return ($env{'form.grade_target'});
  115:         } elsif ($env{'form.grade_target'} eq 'answer') {
  116:             if ($env{'form.answer_output_mode'} eq 'tex') {
  117:                 return ($env{'form.grade_target'});
  118:             }
  119:         }
  120: 	if ($env{'form.webgrade'} &&
  121: 	    ($Apache::lonhomework::modifygrades eq 'F'
  122: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
  123: 	    return ('grade','webgrade');
  124: 	}
  125: 	if ( defined($env{'form.submitted'}) &&
  126: 	     ( !defined($env{'form.newrandomization'}))) {
  127: 	    return ('grade', 'web');
  128: 	} else {
  129: 	    return ('web');
  130: 	}
  131:     } elsif ($env{'request.state'} eq "construct") {
  132: 	if ( defined($env{'form.grade_target'}) ) {
  133: 	    return ($env{'form.grade_target'});
  134: 	}
  135: 	if ( defined($env{'form.preview'})) {
  136: 	    if ( defined($env{'form.submitted'})) {
  137: 		return ('grade', 'web');
  138: 	    } else {
  139: 		return ('web');
  140: 	    }
  141: 	} else {
  142: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
  143: 		#$env{'form.webgrade'} = 'yes';
  144: 		return ('grade','webgrade','answer');
  145: 	    } elsif (($env{'form.problemmode'} eq 'view') ||
  146: 		     ($env{'form.problemmode'} eq 'discard')) {
  147: 		if ( defined($env{'form.submitted'}) &&
  148: 		     (!defined($env{'form.resetdata'})) &&
  149: 		     (!defined($env{'form.newrandomization'}))) {
  150: 		    return ('grade', 'web','answer');
  151: 		} else {
  152: 		    return ('web','answer');
  153: 		}
  154: 	    } elsif ($env{'form.problemmode'} eq 'edit') {
  155: 		if ( $env{'form.submitted'} eq 'edit' ) {
  156: 		    if ( $env{'form.submitbutton'} eq &mt('Save and View') ) {
  157: 			return ('modified','web','answer');
  158: 		    } else {
  159: 			return ('modified','no_output_web','edit');
  160: 		    }
  161: 		} else {
  162: 		    return ('no_output_web','edit');
  163: 		}
  164: 	    } else {
  165: 		return ('web');
  166: 	    }
  167: 	}
  168:     }
  169:     return ();
  170: }
  171: 
  172: sub setup_vars {
  173:     my ($target) = @_;
  174:     return ';'
  175: #  return ';$external::target='.$target.';';
  176: }
  177: 
  178: sub createmenu {
  179:     my ($which,$request)=@_;
  180:     if ($which eq 'grade') {
  181: 	$request->print('<script type="text/javascript" language="JavaScript"> 
  182:           hwkmenu=window.open("/res/adm/pages/homeworkmenu.html","homeworkremote",
  183:                  "height=350,width=150,menubar=no");
  184:           </script>');
  185:     }
  186: }
  187: 
  188: sub proctor_checked_in {
  189:     my ($slot_name,$slot,$type)=@_;
  190:     my @possible_proctors=split(",",$slot->{'proctor'});
  191:     
  192:     return 1 if (!@possible_proctors);
  193: 
  194:     my $key;
  195:     if ($type eq 'Task') {
  196: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
  197: 	$key ="resource.$version.0.checkedin";
  198:     } elsif ($type eq 'problem') {
  199: 	$key ='resource.0.checkedin';
  200:     }
  201:     # backward compatability, used to be username@domain, 
  202:     # now is username:domain
  203:     my $who = $Apache::lonhomework::history{$key};
  204:     if ($who !~ /:/) {
  205: 	$who =~ tr/@/:/;
  206:     }     
  207:     foreach my $possible (@possible_proctors) { 
  208: 	if ($who eq $possible
  209: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
  210: 	    return 1;
  211: 	}
  212:     }
  213:     
  214:     return 0;
  215: }
  216: 
  217: sub check_slot_access {
  218:     my ($id,$type)=@_;
  219: 
  220:     # does it pass normal muster
  221:     my ($status,$datemsg)=&check_access($id);
  222:     
  223:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots");
  224:     if ($useslots ne 'resource' && $useslots ne 'map' 
  225: 	&& $useslots ne 'map_map') {
  226: 	return ($status,$datemsg);
  227:     }
  228: 
  229:     if ($status eq 'SHOW_ANSWER' ||
  230: 	$status eq 'CLOSED' ||
  231: 	$status eq 'INVALID_ACCESS' ||
  232: 	$status eq 'UNAVAILABLE') {
  233: 	return ($status,$datemsg);
  234:     }
  235:     if ($env{'request.state'} eq "construct") {
  236: 	return ($status,$datemsg);
  237:     }
  238:     
  239:     if ($type eq 'Task') {
  240: 	my $version=$Apache::lonhomework::history{'resource.version'};
  241: 	if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
  242: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
  243: 	    return ('SHOW_ANSWER');
  244: 	}
  245:     }
  246: 
  247:     my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent");
  248:     my $available = &Apache::lonnet::EXT("resource.0.available");
  249:     my @slots= (split(':',$availablestudent),split(':',$available));
  250: 
  251: #    if (!@slots) {
  252: #	return ($status,$datemsg);
  253: #    }
  254:     my $slotstatus='NOT_IN_A_SLOT';
  255:     my ($returned_slot,$slot_name);
  256:     foreach my $slot (@slots) {
  257: 	$slot =~ s/(^\s*|\s*$)//g;
  258: 	&Apache::lonxml::debug("getting $slot");
  259: 	my %slot=&Apache::lonnet::get_slot($slot);
  260: 	&Apache::lonhomework::showhash(%slot);
  261: 	if ($slot{'starttime'} < time &&
  262: 	    $slot{'endtime'} > time &&
  263: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
  264: 	    &Apache::lonxml::debug("$slot is good");
  265: 	    $slotstatus='NEEDS_CHECKIN';
  266: 	    $returned_slot=\%slot;
  267: 	    $slot_name=$slot;
  268: 	    last;
  269: 	}
  270:     }
  271:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
  272: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
  273: 	&Apache::lonxml::debug("proctor checked in");
  274: 	$slotstatus=$status;
  275:     }
  276: 
  277:     my ($is_correct,$got_grade,$checkedin);
  278:     if ($type eq 'Task') {
  279: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
  280: 	$got_grade = 
  281: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
  282: 	     =~ /^(?:pass|fail)$/);
  283: 	$is_correct =  
  284: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
  285: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
  286: 	$checkedin =
  287: 	    $Apache::lonhomework::history{"resource.$version.0.checkedin"};
  288:     } elsif ($type eq 'problem') {
  289: 	$got_grade  = 1;
  290: 	$checkedin  = $Apache::lonhomework::history{"resource.0.checkedin"};
  291: 	$is_correct =
  292: 	    ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
  293:     }
  294:     
  295:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
  296:     
  297:     # no slot is currently open, and has been checked in for this version
  298:     # but hasn't got a grade, therefore must be awaiting a grade
  299:     if (!defined($slot_name)
  300: 	&& $checkedin 
  301: 	&& !$got_grade) {
  302: 	return ('WAITING_FOR_GRADE');
  303:     }
  304: 
  305:     # Previously used slot is no longer open, and has been checked in for this version.
  306:     # However, the problem is not closed, and potentially, another slot might be
  307:     # used to gain access to it to work on it, until the due date is reached, and the
  308:     # problem then becomes CLOSED.  Therefore return the slotstatus - 
  309:     # (which will be NOT_IN_SLOT).
  310:     if (!defined($slot_name)
  311: 	&& $checkedin 
  312: 	&& $type eq 'problem') {
  313:         return ($slotstatus);
  314:     }
  315: 
  316:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
  317: 	&& $checkedin ) {
  318: 
  319: 	if ($got_grade) {
  320: 	    return ('SHOW_ANSWER');
  321: 	} else {
  322: 	    return ('WAITING_FOR_GRADE');
  323: 	}
  324: 
  325:     }
  326: 
  327:     if ( $is_correct) {
  328: 	if ($type eq 'problem') {
  329: 	    return ($status);
  330: 	}
  331: 	return ('SHOW_ANSWER');
  332:     }
  333: 
  334:     if ( $status eq 'CANNOT_ANSWER' && 
  335: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
  336: 	return ($status,$datemsg);
  337:     }
  338: 
  339:     return ($slotstatus,$datemsg,$slot_name,$returned_slot);
  340: }
  341: 
  342: # JB, 9/24/2002: Any changes in this function may require a change
  343: # in lonnavmaps::resource::getDateStatus.
  344: sub check_access {
  345:     my ($id) = @_;
  346:     my $date ='';
  347:     my $status;
  348:     my $datemsg = '';
  349:     my $lastdate = '';
  350:     my $type;
  351:     my $passed;
  352: 
  353:     if ($env{'request.state'} eq "construct") {
  354: 	if ($env{'form.problemstate'}) {
  355: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
  356: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
  357: 			&& &hide_problem_status())) {
  358: 		    return ('CANNOT_ANSWER',
  359: 			    &mt('is in this state due to author settings.'));
  360: 		}
  361: 	    } else {
  362: 		return ($env{'form.problemstate'},
  363: 			&mt('is in this state due to author settings.'));
  364: 	    }
  365: 	}
  366: 	&Apache::lonxml::debug("in construction ignoring dates");
  367: 	$status='CAN_ANSWER';
  368: 	$datemsg=&mt('is in under construction');
  369: #	return ($status,$datemsg);
  370:     }
  371: 
  372:     &Apache::lonxml::debug("checking for part :$id:");
  373:     &Apache::lonxml::debug("time:".time);
  374: 
  375:     my ($symb)=&Apache::lonnet::whichuser();
  376:     &Apache::lonxml::debug("symb:".$symb);
  377:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
  378:     if ($env{'request.state'} ne "construct") {
  379:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc");
  380: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
  381: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
  382: 	    $status='INVALID_ACCESS';
  383: 	    $date=&mt("can not be accessed from your location.");
  384: 	    return($status,$date);
  385: 	}
  386: 	
  387: 	foreach my $temp ("opendate","duedate","answerdate") {
  388: 	    $lastdate = $date;
  389: 	    if ($temp eq 'duedate') {
  390: 		$date = &due_date($id);
  391: 	    } else {
  392: 		$date = &Apache::lonnet::EXT("resource.$id.$temp");
  393: 	    }
  394: 	    
  395: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type");
  396: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
  397: 		$date     =~ /^(con_lost|no_such_host)/) {
  398: 		$status='UNAVAILABLE';
  399: 		$date=&mt("may open later.");
  400: 		return($status,$date);
  401: 	    }
  402: 	    if ($thistype eq 'date_interval') {
  403: 		if ($temp eq 'opendate') {
  404: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")-$date;
  405: 		}
  406: 		if ($temp eq 'answerdate') {
  407: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate")+$date;
  408: 		}
  409: 	    }
  410: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
  411: 	    if ($date eq '') {
  412: 		$date = &mt("an unknown date"); $passed = 0;
  413: 	    } elsif ($date eq 'con_lost') {
  414: 		$date = &mt("an indeterminate date"); $passed = 0;
  415: 	    } else {
  416: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
  417: 		$date = &Apache::lonlocal::locallocaltime($date);
  418: 	    }
  419: 	    if (!$passed) { $type=$temp; last; }
  420: 	}
  421: 	&Apache::lonxml::debug("have :$type:$passed:");
  422: 	if ($passed) {
  423: 	    $status='SHOW_ANSWER';
  424: 	    $datemsg=$date;
  425: 	} elsif ($type eq 'opendate') {
  426: 	    $status='CLOSED';
  427: 	    $datemsg = &mt("will open on")." $date";
  428: 	} elsif ($type eq 'duedate') {
  429: 	    $status='CAN_ANSWER';
  430: 	    $datemsg = &mt("is due at")." $date";
  431: 	} elsif ($type eq 'answerdate') {
  432: 	    $status='CLOSED';
  433: 	    $datemsg = &mt("was due on")." $lastdate".&mt(", and answers will be available on")." $date";
  434: 	}
  435:     }
  436:     if ($status eq 'CAN_ANSWER' ||
  437: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
  438: 	#check #tries, and if correct.
  439: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
  440: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries");
  441: 	if ( $tries eq '' ) { $tries = '0'; }
  442: 	if ( $maxtries eq '' && 
  443: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
  444: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
  445: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
  446: 	if(($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/
  447: 	    &&
  448: 	    &show_problem_status())
  449: 	   ||
  450: 	   $Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
  451: 	    $status = 'CANNOT_ANSWER';
  452: 	}
  453: 	if ($status eq 'CANNOT_ANSWER'
  454: 	    && &show_answer_problem_status()) {
  455: 	    $status = 'SHOW_ANSWER';
  456: 	}
  457:     }
  458:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
  459: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval");
  460: 	&Apache::lonxml::debug("looking for interval @interval");
  461: 	if ($interval[0]) {
  462: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1]);
  463: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
  464: 	    if (!$first_access) {
  465: 		$status='NOT_YET_VIEWED';
  466: 		my $due_date = &due_date($id);
  467: 		my $seconds_left = $due_date - time;
  468: 		if ($seconds_left > $interval[0] || $due_date eq '') {
  469: 		    $seconds_left = $interval[0];
  470: 		}
  471: 		$datemsg=&seconds_to_human_length($seconds_left);
  472: 	    }
  473: 	}
  474:     }
  475: 
  476:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
  477:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
  478:   #    return ('UNCHECKEDOUT','needs to be checked out');
  479:   #}
  480: 
  481: 
  482:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
  483:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
  484: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
  485: 	$status='CAN_ANSWER';
  486: 	$datemsg=&mt('is closed but you are allowed to view it');
  487:     }
  488: 
  489:     return ($status,$datemsg);
  490: }
  491: # this should work exactly like the copy in lonnavmaps.pm
  492: sub due_date {
  493:     my ($part_id,$symb,$udom,$uname)=@_;
  494:     my $date;
  495:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
  496: 				       $udom,$uname);
  497:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
  498:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
  499: 				       $udom,$uname);
  500:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
  501:     if ($interval[0] =~ /\d+/) {
  502: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
  503: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
  504: 	if (defined($first_access)) {
  505: 	    my $interval = $first_access+$interval[0];
  506: 	    $date = (!$due_date || $interval < $due_date) ? $interval
  507:                                                           : $due_date;
  508: 	} else {
  509: 	    $date = $due_date;
  510: 	}
  511:     } else {
  512: 	$date = $due_date;
  513:     }
  514:     return $date
  515: }
  516: 
  517: sub seconds_to_human_length {
  518:     my ($length)=@_;
  519: 
  520:     my $seconds=$length%60; $length=int($length/60);
  521:     my $minutes=$length%60; $length=int($length/60);
  522:     my $hours=$length%24;   $length=int($length/24);
  523:     my $days=$length;
  524: 
  525:     my $timestr;
  526:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
  527:     if ($hours > 0) { $timestr.=($timestr?", ":"").
  528: 			  &mt('[quant,_1,hour]',$hours); }
  529:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
  530: 			    &mt('[quant,_1,minute]',$minutes); }
  531:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
  532: 			    &mt('[quant,_1,second]',$seconds); }
  533:     return $timestr;
  534: }
  535: 
  536: sub showhash {
  537:     my (%hash) = @_;
  538:     &showhashsubset(\%hash,'.');
  539:     return '';
  540: }
  541: 
  542: sub showarray {
  543:     my ($array)=@_;
  544:     my $string="(";
  545:     foreach my $elm (@{ $array }) {
  546: 	if (ref($elm) eq 'ARRAY') {
  547: 	    $string.=&showarray($elm);
  548: 	} elsif (ref($elm) eq 'HASH') {
  549: 	    $string.= "HASH --- \n<br />";
  550: 	    $string.= &showhashsubset($elm,'.');
  551: 	} else {
  552: 	    $string.="$elm,"
  553: 	}
  554:     }
  555:     chop($string);
  556:     $string.=")";
  557:     return $string;
  558: }
  559: 
  560: sub showhashsubset {
  561:     my ($hash,$keyre) = @_;
  562:     my $resultkey;
  563:     foreach $resultkey (sort keys %$hash) {
  564: 	if ($resultkey !~ /$keyre/) { next; }
  565: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
  566: 	    &Apache::lonxml::debug("$resultkey ---- ".
  567: 				   &showarray($$hash{$resultkey}));
  568: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
  569: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  570: 	    &showhashsubset($$hash{$resultkey},'.');
  571: 	} else {
  572: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
  573: 	}
  574:     }
  575:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
  576:     return '';
  577: }
  578: 
  579: sub setuppermissions {
  580:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
  581:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
  582:     if (! $viewgrades && 
  583: 	exists($env{'request.course.sec'}) && 
  584: 	$env{'request.course.sec'} !~ /^\s*$/) {
  585: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
  586:                                                '/'.$env{'request.course.sec'});
  587:     }
  588:     $Apache::lonhomework::viewgrades = $viewgrades;
  589: 
  590:     if ($Apache::lonhomework::browse eq 'F' && 
  591: 	$env{'form.devalidatecourseresdata'} eq 'on') {
  592: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
  593: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
  594: 					      $env{"course.$courseid.domain"});
  595:     }
  596: 
  597:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
  598:     if (! $modifygrades && 
  599: 	exists($env{'request.course.sec'}) && 
  600: 	$env{'request.course.sec'} !~ /^\s*$/) {
  601: 	$modifygrades = 
  602: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
  603: 				     '/'.$env{'request.course.sec'});
  604:     }
  605:     $Apache::lonhomework::modifygrades = $modifygrades;
  606: 
  607:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
  608:     if (! $queuegrade && 
  609: 	exists($env{'request.course.sec'}) && 
  610: 	$env{'request.course.sec'} !~ /^\s*$/) {
  611: 	$queuegrade = 
  612: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
  613: 				     '/'.$env{'request.course.sec'});
  614:     }
  615:     $Apache::lonhomework::queuegrade = $queuegrade;
  616:     return '';
  617: }
  618: 
  619: sub unset_permissions {
  620:     undef($Apache::lonhomework::queuegrade);
  621:     undef($Apache::lonhomework::modifygrades);
  622:     undef($Apache::lonhomework::viewgrades);
  623:     undef($Apache::lonhomework::browse);
  624: }
  625: 
  626: sub setupheader {
  627:     my $request=$_[0];
  628:     &Apache::loncommon::content_type($request,'text/html');
  629:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
  630: 	&Apache::loncommon::no_cache($request);
  631:     }
  632: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
  633: #							  'lastrevisiondate'));
  634:     $request->send_http_header;
  635:     return OK if $request->header_only;
  636:     return ''
  637: }
  638: 
  639: sub handle_save_or_undo {
  640:     my ($request,$problem,$result) = @_;
  641:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
  642:     my $filebak =$file.".bak";
  643:     my $filetmp =$file.".tmp";
  644:     my $error=0;
  645:     if ($env{'form.Undo'} eq &mt('undo')) {
  646: 	my $error=0;
  647: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
  648: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
  649: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
  650: 	if (!$error) {
  651: 	    &Apache::lonxml::info("<p><b>".
  652: 				  &mt("Undid changes, Switched [_1] and [_2]",
  653: 				      '<span class="LC_filename">'.$filebak.
  654: 				      '</span>',
  655: 				      '<span class="LC_filename">'.$file.
  656: 				      '</span>')."</b></p>");
  657: 	} else {
  658: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
  659: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
  660: 				      '<span class="LC_filename">'.
  661: 				      $filebak.'</span>',
  662: 				      '<span class="LC_filename">'.
  663: 				      $file.'</span>')."</span></p>");
  664: 	    $error=1;
  665: 	}
  666:     } else {
  667:         &Apache::lonnet::correct_line_ends($result);
  668: 	my $fs=Apache::File->new(">$filebak");
  669: 	if (defined($fs)) {
  670: 	    print $fs $$problem;
  671: 	} else {
  672: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
  673: 				  &mt("Unable to make backup [_1]",
  674: 				      '<span class="LC_filename">'.
  675: 				      $filebak.'</span>')."</span>");
  676: 	    $error=2;
  677: 	}
  678: 	my $fh=Apache::File->new(">$file");
  679: 	if (defined($fh)) {
  680: 	    print $fh $$result;
  681: 	} else {
  682: 	    &Apache::lonxml::info('<span class="LC_error">'.
  683: 				  &mt("Unable to write to [_1]",
  684: 				      '<span class="LC_filename">'.
  685: 				      $file.'</span>').
  686: 				  '</span>');
  687: 	    $error|=4;
  688: 	}
  689:     }
  690:     return $error;
  691: }
  692: 
  693: sub analyze_header {
  694:     my ($request) = @_;
  695:     my $js = &Apache::structuretags::setmode_javascript();
  696: 
  697:     # Breadcrumbs
  698:     my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
  699:                    'text' => 'Construction Space'},
  700:                   {'href' => '',
  701:                    'text' => 'Problem Testing'},
  702:                   {'href' => '',
  703:                    'text' => 'Analyzing a problem'}];
  704: 
  705:     my $result =
  706:         &Apache::loncommon::start_page('Analyzing a problem',
  707:                                        $js,
  708:                                        {'bread_crumbs' => $brcrum,})
  709:        .&Apache::loncommon::head_subbox(
  710:                 &Apache::loncommon::CSTR_pageheader());
  711:     $result .= 
  712: 	&Apache::lonxml::message_location().'
  713:             <form name="lonhomework" method="post" action="'.
  714: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
  715:             '<input type="hidden" name="problemmode" value="'.
  716:             $env{'form.problemmode'}.'" />'.
  717: 	    &Apache::structuretags::remember_problem_state().'
  718:             <div class="LC_edit_problem_analyze_header">
  719:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
  720:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
  721:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
  722:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
  723:             <hr />
  724:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
  725:             'onclick="javascript:setmode(this.form,'."'view'".')" />
  726:             <hr />
  727:             </div>
  728:             </form>';
  729:     &Apache::lonxml::add_messages(\$result);
  730:     $request->print($result);
  731:     $request->rflush();
  732: }
  733: 
  734: sub analyze_footer {
  735:     my ($request) = @_;
  736:     $request->print(&Apache::loncommon::end_page());
  737:     $request->rflush();
  738: }
  739: 
  740: sub analyze {
  741:     my ($request,$file) = @_;
  742:     &Apache::lonxml::debug("Analyze");
  743:     my $result;
  744:     my %overall;
  745:     my %seedexample;
  746:     my %allparts;
  747:     my $rndseed=$env{'form.rndseed'};
  748:     &analyze_header($request);
  749:     my %prog_state=
  750: 	&Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
  751: 					      &mt('Getting Problem Variants'),
  752: 					      $env{'form.numtoanalyze'},
  753: 					      'inline',undef);
  754:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
  755: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
  756: 						 &mt('last problem'));
  757: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
  758:         my $thisseed=$i+$rndseed;
  759: 	my $subresult=&Apache::lonnet::ssi($request->uri,
  760: 					   ('grade_target' => 'analyze'),
  761: 					   ('rndseed' => $thisseed));
  762: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
  763: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  764: 	my @parts;
  765: 	if (defined(@{ $analyze{'parts'} })) {
  766: 	    @parts=@{ $analyze{'parts'} };
  767: 	}
  768: 	foreach my $part (@parts) {
  769: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
  770: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
  771: 		$analyze{$part.'.type'} eq 'stringresponse'	||
  772: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
  773: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
  774: 		    my $i=0;
  775: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
  776: 			push( @{ $overall{$part.'.answer'}[$i] },
  777: 			      $answer_part);
  778: 			my $concatanswer= join("\0",@{ $answer_part });
  779: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
  780: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
  781: 			}
  782: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
  783: 			    $thisseed;
  784: 			$i++;
  785: 		    }
  786: 		}
  787: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
  788: 		    my $answer_part = 
  789: 			['<span class="LC_error">'.&mt('Error').'</span>'];
  790: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
  791: 			$thisseed;
  792: 		    push( @{ $overall{$part.'.answer'}[0] },
  793: 			  $answer_part);
  794: 		}
  795: 	    }
  796: 	}
  797:     }
  798:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
  799: 					  &mt('Analyzing Results'));
  800:     $request->print('<hr />'
  801:                    .'<h3>'
  802:                    .&mt('List of possible answers')
  803:                    .'</h3>'
  804:     );
  805:     foreach my $part (sort(keys(%allparts))) {
  806: 	if (defined(@{ $overall{$part.'.answer'} })) {
  807: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
  808: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
  809:                 $request->print(&Apache::loncommon::start_data_table()
  810:                                .&Apache::loncommon::start_data_table_header_row()
  811:                                .'<th colspan="'.($num_cols+1).'">'
  812:                                .&mt('Part').' '.$part
  813:                 );
  814: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
  815: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
  816: 		}
  817: 		$request->print('</th>'
  818:                                .&Apache::loncommon::end_data_table_header_row()
  819:                 );
  820: 		my %frequency;
  821: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
  822: 		    $frequency{join("\0",@{ $answer })}++;
  823: 		}
  824:                 $request->print(&Apache::loncommon::start_data_table_header_row()
  825:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
  826:                                .'<th>'.&mt('Frequency').'<br />'
  827:                                .'('.&mt('click for example').')</th>'
  828:                                .&Apache::loncommon::end_data_table_header_row()
  829:                 );
  830: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
  831:                     $request->print(&Apache::loncommon::start_data_table_row()
  832:                                    .'<td>'
  833:                                    .join('</td><td>',split("\0",$answer))
  834: 				   .'</td>'
  835:                                    .'<td>'
  836:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
  837: 				   .'</td>'
  838:                                    .&Apache::loncommon::end_data_table_row()
  839:                     );
  840: 		}
  841:                 $request->print(&Apache::loncommon::end_data_table());
  842: 	    }
  843: 	} else {
  844:             $request->print('<p class="LC_warning">'
  845:                            .&mt('Response [_1] is not analyzable at this time.',$part)
  846: 			   .'</p>'
  847:             );
  848: 	}
  849:     }
  850:     if (scalar(keys(%allparts)) == 0 ) {
  851:         $request->print('<p class="LC_warning">'
  852:                        .&mt('Found no analyzable responses in this problem.'
  853:                            .' Currently only Numerical, Formula and String response styles are supported.')
  854:                        .'</p>'
  855:         );
  856:     }
  857:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
  858:     &analyze_footer($request);
  859:     &Apache::lonhomework::showhash(%overall);
  860:     return $result;
  861: }
  862: 
  863: {
  864:     my $show_problem_status;
  865:     sub reset_show_problem_status {
  866: 	undef($show_problem_status);
  867:     }
  868: 
  869:     sub set_show_problem_status {
  870: 	my ($new_status) = @_;
  871: 	$show_problem_status = lc($new_status);
  872:     }
  873: 
  874:     sub hide_problem_status {
  875: 	return ($show_problem_status eq 'no'
  876: 		|| $show_problem_status eq 'no_feedback_ever');
  877:     }
  878: 
  879:     sub show_problem_status {
  880: 	return ($show_problem_status eq 'yes'
  881: 		|| $show_problem_status eq 'answer'
  882: 		|| $show_problem_status eq '');
  883:     }
  884:     
  885:     sub show_some_problem_status {
  886: 	return ($show_problem_status eq 'no');
  887:     }
  888: 
  889:     sub show_no_problem_status {
  890: 	return ($show_problem_status eq 'no_feedback_ever');
  891:     }
  892:   
  893:     sub show_answer_problem_status {
  894: 	return ($show_problem_status eq 'answer');
  895:     }
  896: }
  897: 
  898: sub editxmlmode {
  899:     my ($request,$file) = @_;
  900:     my $result;
  901:     my $problem=&Apache::lonnet::getfile($file);
  902:     if ($problem eq -1) {
  903: 	&Apache::lonxml::error(
  904:             '<b> '
  905:            .&mt('Unable to find [_1]',
  906:                 '<span class="LC_filename">'.$file.'</span>')
  907:            .'</b>');
  908: 
  909: 	$problem='';
  910:     }
  911:     if (defined($env{'form.editxmltext'}) || defined($env{'form.Undo'})) {
  912: 	my $error=&handle_save_or_undo($request,\$problem,
  913: 				       \$env{'form.editxmltext'});
  914: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
  915:     }
  916:     &Apache::lonhomework::showhashsubset(\%env,'^form');
  917:     if ( $env{'form.submitbutton'} eq &mt('Save and View') ) {
  918: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
  919: 	$env{'form.problemmode'}='view';
  920: 	&renderpage($request,$file);
  921:     } else {
  922: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
  923: 	if ($cols > 80) { $cols = 80; }
  924: 	if ($cols < 70) { $cols = 70; }
  925: 	if ($rows < 20) { $rows = 20; }
  926: 	my $js =
  927: 	    &Apache::edit::js_change_detection(). 
  928: 	    &Apache::loncommon::resize_textarea_js().
  929:             &Apache::structuretags::setmode_javascript().
  930:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
  931: 	my $only_body =  ($env{'environment.remote'} eq 'off')? 0 : 1;
  932: 	my $dragmath_button = 
  933:             &Apache::lonhtmlcommon::dragmath_button("LC_editxmltext",1);
  934: 
  935:     # Breadcrumbs
  936:     my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
  937:                    'text' => 'Construction Space'},
  938:                   {'href' => '',
  939:                    'text' => 'Problem Editing'}];
  940: 
  941: 	my $start_page = 
  942: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
  943: 					   {'no_auto_mt_title' => 1,
  944: 					    'only_body'        => $only_body,
  945: 					    'add_entries'      => {
  946: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
  947: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
  948:                                     },
  949:                                                 'bread_crumbs' => $brcrum,
  950: });
  951: 
  952:     $result=$start_page
  953:            .&Apache::loncommon::head_subbox(
  954:                 &Apache::loncommon::CSTR_pageheader());
  955: 	$result.=&renderpage($request,$file,['no_output_web'],1).
  956:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
  957: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
  958: 	    &Apache::structuretags::remember_problem_state().'
  959:             <div class="LC_edit_problem_editxml_header">
  960:               <table class="LC_edit_problem_header_title"><tr><td>
  961:                <h2>'.&mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').'</h2>
  962:                 </td><td align="right">
  963:                   '.&Apache::loncommon::helpLatexCheatsheet('Problem_LON-CAPA_Functions','Script Functions').'
  964:                 </td></tr>
  965:               </table>
  966:               <div class="LC_edit_problem_discards">
  967:                 <input type="hidden" name="problemmode" value="editxml" />
  968: 
  969:                 <input type="button" name="submitmode" accesskey="d" value="'.&mt('Discard Edits and View').'" '.
  970:                 'onclick="javascript:setmode(this.form,'."'discard'".')" />
  971:                 <input type="button" '.&Apache::edit::submit_ask_anyway('setmode(this.form,'."'edit'".')').'name="submitmode" accesskey="e" value="'.&mt('Edit').'" />
  972:                 <input type="submit" name="Undo" accesskey="u" value="'.&mt('undo').'" />
  973:                 '.$dragmath_button.'
  974:               </div>
  975:               <div class="LC_edit_problem_saves">
  976:                 <input type="submit" name="submitbutton" accesskey="s" value="'.&mt('Save').'"  />
  977:                 <input type="submit" name="submitbutton" accesskey="v" value="'.&mt('Save and View').'" />
  978:               </div>
  979:               <hr style="clear:both;" />
  980: 	      '.&Apache::lonxml::message_location().'
  981:             </div>
  982:             '  . '
  983:             <textarea '.&Apache::edit::element_change_detection().
  984: 	              ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" '.
  985: 		      ' name="editxmltext" id="LC_editxmltext">'.
  986: 		      &HTML::Entities::encode($problem,'<>&"').'</textarea>
  987:             <div id="LC_aftertextarea">
  988:             </div>
  989:             </form>'.&Apache::loncommon::end_page();
  990: 	&Apache::lonxml::add_messages(\$result);
  991: 	$request->print($result);
  992:     }
  993:     return '';
  994: }
  995: 
  996: #
  997: #    Render the page in whatever target desired.
  998: #
  999: sub renderpage {
 1000:     my ($request,$file,$targets,$return_string) = @_;
 1001: 
 1002:     my @targets = @{$targets || [&get_target()]};
 1003:     &Apache::lonhomework::showhashsubset(\%env,'form.');
 1004:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
 1005: 
 1006:     my $overall_result;
 1007:     foreach my $target (@targets) {
 1008: 	# FIXME need to do something intelligent when a problem goes
 1009:         # from viewable to not viewable due to map conditions
 1010: 	#&setuppermissions();
 1011: 	#if (   $Apache::lonhomework::browse ne '2'
 1012: 	#    && $Apache::lonhomework::browse ne 'F' ) {
 1013: 	#    $request->print(" You most likely shouldn't see me.");
 1014: 	#}
 1015: 	#my $t0 = [&gettimeofday()];
 1016: 	my $output=1;
 1017: 	if ($target eq 'no_output_web') {
 1018: 	    $target = 'web'; $output=0;
 1019: 	}
 1020: 	my $problem=&Apache::lonnet::getfile($file);
 1021: 	my $result;
 1022: 	if ($problem eq -1) {
 1023: 	    $problem='';
 1024: 	    my $filename=(split('/',$file))[-1];
 1025: 	    my $error =
 1026: 		"<b> ".&mt('Unable to find [_1]',
 1027: 			   '<span class="LC_filename">'.$filename.'</span>')
 1028: 		."</b>";
 1029: 	    $result.=
 1030: 		&Apache::loncommon::simple_error_page($request,'Not available',
 1031: 						      $error);
 1032: 	    return;
 1033: 	}
 1034: 
 1035: 	my %mystyle;
 1036: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
 1037: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
 1038: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
 1039: 
 1040: 	&Apache::lonxml::debug("Should be parsing now");
 1041: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
 1042: 					     &setup_vars($target),%mystyle);
 1043: 	&finished_parsing();
 1044: 	if (!$output) { $result = ''; }
 1045: 	#$request->print("Result follows:");
 1046: 	if ($target eq 'modified') {
 1047: 	    &handle_save_or_undo($request,\$problem,\$result);
 1048: 	} else {
 1049: 	    if ($target eq 'analyze') {
 1050: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
 1051: 		undef(%Apache::lonhomework::analyze);
 1052: 	    }
 1053: 	    #my $td=&tv_interval($t0);
 1054: 	    #if ( $Apache::lonxml::debug) {
 1055: 	    #$result =~ s:</body>::;
 1056: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
 1057: 	    #}
 1058: #	    $request->print($result);
 1059: 	    $overall_result.=$result;
 1060: #	    $request->rflush();
 1061: 	}
 1062: 	#$request->print(":Result ends");
 1063: 	#my $td=&tv_interval($t0);
 1064:     }
 1065:     if (!$return_string) {
 1066: 	&Apache::lonxml::add_messages(\$overall_result);
 1067: 	$request->print($overall_result);   
 1068: 	$request->rflush();   
 1069:     } else {
 1070: 	return $overall_result;
 1071:     }
 1072: }
 1073: 
 1074: sub finished_parsing {
 1075:     undef($Apache::lonhomework::parsing_a_problem);
 1076:     undef($Apache::lonhomework::parsing_a_task);
 1077: }
 1078: 
 1079: sub get_template_list {
 1080:     my ($extension) = @_;
 1081:     my $result;
 1082:     my @allnames;
 1083:     &Apache::lonxml::debug("Looking for :$extension:");
 1084:     my $glob_extension  = $extension;
 1085:     if ($extension eq 'survey' || $extension eq 'exam') {
 1086: 	$glob_extension = 'problem';
 1087:     }
 1088:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
 1089: 		     '/templates/*.'.$glob_extension);
 1090:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
 1091:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
 1092:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
 1093:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
 1094:     my ($midpoint,$seconddiv,$numfiles);
 1095:     $numfiles = 0;
 1096:     foreach my $file (@files) {
 1097:         next if ($file->[1] !~ /\S/);
 1098:         $numfiles ++;
 1099:     }
 1100:     if ($numfiles > 0) {
 1101:         $result = '<div class="LC_left_float">';
 1102:         $midpoint = int($numfiles/2);
 1103:         if ($numfiles%2) {
 1104:             $midpoint ++;
 1105:         }
 1106:     }
 1107:     my $count = 0;
 1108:     my $currentcategory='';
 1109:     my $first = 1;
 1110:     foreach my $file (@files) {
 1111: 	next if ($file->[1] !~ /\S/);
 1112:         if ($file->[2] ne $currentcategory) {
 1113:            $currentcategory=$file->[2];
 1114:            if ((!$seconddiv) && ($count >= $midpoint)) {
 1115:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
 1116:                $seconddiv = 1;
 1117:            } elsif (!$first) {
 1118:                $result.='</div>'."\n";
 1119:            } else {
 1120:                $first = 0;
 1121:            }
 1122:            $result.= '<div class="LC_Box">'."\n"
 1123:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
 1124:            $count++;
 1125:         }
 1126: 	$result .=
 1127: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
 1128: 	    $file->[1].'</label>';
 1129:         if ($file->[3]) {
 1130:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
 1131:         }
 1132:         my $filename=$file->[0];
 1133:         $filename=~s/^\/home\/httpd\/html//;
 1134:         $result.=' <span class="LC_fontsize_small">'
 1135:                 .'<a href="'.$filename.'?inhibitmenu=yes" target="sample">'.&mt('Example').'</a>'
 1136:                 .'</span><br />'."\n";
 1137:         $count ++;
 1138:     }
 1139:     if ($numfiles > 0) {
 1140:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
 1141:     }
 1142:     return $result;
 1143: }
 1144: 
 1145: sub newproblem {
 1146:     my ($request) = @_;
 1147: 
 1148:     if ($env{'form.template'}) {
 1149: 	my $file = $env{'form.template'};
 1150: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1151: 	&File::Copy::copy($file,$dest);
 1152: 	&renderpage($request,$dest);
 1153: 	return;
 1154:     }
 1155: 
 1156:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
 1157:     &Apache::lonxml::debug("Looking for :$extension:");
 1158:     my $templatelist=&get_template_list($extension);
 1159:     if ($env{'form.newfile'} && !$templatelist) {
 1160: 	# no templates found
 1161: 	my $templatefilename =
 1162: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
 1163: 	&Apache::lonxml::debug("$templatefilename");
 1164: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1165: 	&File::Copy::copy($templatefilename,$dest);
 1166: 	&renderpage($request,$dest);
 1167:     } else {
 1168: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
 1169: 	my $shownurl=$url;	
 1170: 	$shownurl=~s-^/~-/priv/-;
 1171: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1172: 	my $errormsg;
 1173: 	my $instructions;
 1174:         my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
 1175:                        'text' => 'Construction Space'},
 1176:                       {'href' => '',
 1177:                        'text' => "Create New $extension"}];
 1178: 	my $start_page = 
 1179:             &Apache::loncommon::start_page("Create New $extension",
 1180:                                            undef,
 1181:                                            {'bread_crumbs' => $brcrum,});
 1182: 	$request->print(
 1183:         $start_page
 1184:        .&Apache::loncommon::head_subbox(
 1185:                 &Apache::loncommon::CSTR_pageheader())
 1186:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
 1187: $errormsg
 1188: ".&mt("The requested file [_1] currently does not exist.",
 1189:       '<span class="LC_filename">'.$shownurl.'</span>').'
 1190: <p class="LC_info">
 1191: '.&mt("To create a new $extension, select a template from the".
 1192:       " list below. Then click on the \"Create $extension\" button.").'
 1193: </p><div><form action="'.$url.'" method="post">');
 1194: 
 1195: 	if (defined($templatelist)) {
 1196: 	    $request->print($templatelist);
 1197: 	}
 1198: 	$request->print('<br /><input type="submit" name="newfile" value="'.
 1199: 			&mt("Create $extension").'" />');
 1200: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
 1201:     }
 1202:     return;
 1203: }
 1204: 
 1205: sub update_construct_style {
 1206:     if ($env{'request.state'} eq "construct"
 1207: 	&& $env{'form.problemmode'} eq 'view' 
 1208: 	&&  defined($env{'form.submitted'})
 1209: 	&& !defined($env{'form.resetdata'})
 1210: 	&& !defined($env{'form.newrandomization'})) {
 1211: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
 1212: 	    ||$env{'form.clear_style_file'}) {
 1213: 	    &Apache::lonnet::delenv('construct.style');
 1214: 	} elsif ($env{'form.style_file'} 
 1215: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
 1216: 	    &Apache::lonnet::appenv({'construct.style' => 
 1217: 				        $env{'form.style_file'}});
 1218: 	}
 1219:     }
 1220: }
 1221: 
 1222: 
 1223: sub handler {
 1224:     #my $t0 = [&gettimeofday()];
 1225:     my $request=$_[0];
 1226:     $Apache::lonxml::request=$request;
 1227:     $Apache::lonxml::debug=$env{'user.debug'};
 1228:     $env{'request.uri'}=$request->uri;
 1229:     &setuppermissions();
 1230: 
 1231:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1232: 
 1233:     #check if we know where we are
 1234:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
 1235: 	# if we are browsing we might not be able to know where we are
 1236: 	if ($Apache::lonhomework::browse ne 'F' && 
 1237: 	    $env{'request.state'} ne "construct") {
 1238: 	    #should know where we are, so ask
 1239: 	    &unset_permissions();
 1240: 	    $request->internal_redirect('/adm/ambiguous');
 1241: 	    return OK;
 1242: 	}
 1243:     }
 1244:     if (&setupheader($request)) {
 1245: 	&unset_permissions();
 1246: 	return OK;
 1247:     }
 1248:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
 1249:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
 1250:     my ($symb) = &Apache::lonnet::whichuser();
 1251:     &Apache::lonxml::debug('symb is '.$symb);
 1252:     if ($env{'request.state'} eq "construct") {
 1253: 	if ( -e $file ) {
 1254: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1255: 						    ['problemmode']);
 1256: 	    if (!(defined $env{'form.problemmode'})) {
 1257: 		#first visit to problem in construction space
 1258: 		$env{'form.problemmode'}= 'view';
 1259: 		&renderpage($request,$file);
 1260: 	    } elsif ($env{'form.problemmode'} eq 'editxml') {
 1261: 		&editxmlmode($request,$file);
 1262: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
 1263: 		&analyze($request,$file);
 1264: 	    } else {
 1265: 		&update_construct_style();
 1266: 		&renderpage($request,$file);
 1267: 	    }
 1268: 	} else {
 1269: 	    # requested file doesn't exist in contruction space
 1270: 	    &newproblem($request);
 1271: 	}
 1272:     } else {
 1273: 	# just render the page normally outside of construction space
 1274: 	&Apache::lonxml::debug("not construct");
 1275: 	&renderpage($request,$file);
 1276:     }
 1277:     #my $td=&tv_interval($t0);
 1278:     #&Apache::lonxml::debug("Spent $td seconds processing");
 1279:     # always turn off debug messages
 1280:     $Apache::lonxml::debug=0;
 1281:     &unset_permissions();
 1282:     return OK;
 1283: 
 1284: }
 1285: 
 1286: 1;
 1287: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>