File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.311: download - view: text, annotated - select for diffs
Tue May 19 22:52:19 2009 UTC (14 years, 11 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
To get rid of the title_bar, customized titles aren't allowed anymore.

Moved special title for Construction Space pages from &start_page() to new routine &CSTR_pageheader(). Since &start_page() isn't the only routine called to create the page header, the centralized creation of the CSTR page header code can't be currently called in &start_page(). This needs to be done at each place where &start_page() is called.

First changes to get rid of customized page titles:
- Moved CSTR page header code from start_page to new sub routine &CSTR_pageheader()
- Currently keep old header but use &CSTR_pageheader()
- Directly call &CSTR_pageheader() in CSTR related scripts (lonpubdir.pm, lonhomework.pm, structuretags.pm)
  (More scripts need to call this routine)
- Added new sub routine &head_subbox() to create head_subbox which contains page related links and functions, etc.
- Added styles for &head_subbox()
  (Currently implemented as LC_head_subbox2 to avoid conflicts with code created by lonhtmlcommon::breadcrumbs - will be changed)

Other but related changes:
- Added some breadcrumbs to CSTR
  (Only basic calls - links and structure has to be added/revisited)
- Adjusted styles used for breadcrumbs:
    - Replaced hardcoded border color by dynamical standard border color
    - Removed margin to allow direct concatination with head_subbox

- Added some FIXME comments to mark work in progress

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

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