File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.294: download - view: text, annotated - select for diffs
Tue Jul 1 11:01:30 2008 UTC (15 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
bz 5744 - Add "Edit Math" button to bring up dragmath to edit equations and
insert the text into a resource being edited in xml editor.

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

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