File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.314: download - view: text, annotated - select for diffs
Fri Jul 3 14:52:47 2009 UTC (14 years, 10 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
- Use new Box style for problem template list
  (not so) quick and (not so) dirty solution: way of building categories and two columns should be revisited.
- Corrected nested tags issue (a / font)
- Replaced font tag by style
- XHTML: Replaced "<p><form..." by "<div></form..."
- Corrected unbalanced tags (added missing <div>)
- Use info style for info message about what to do

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Homework handler
    3: #
    4: # $Id: lonhomework.pm,v 1.314 2009/07/03 14:52:47 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: 
  692:     # Breadcrumbs
  693:     my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
  694:                    'text' => 'Construction Space'},
  695:                   {'href' => '',
  696:                    'text' => 'Problem Testing'},
  697:                   {'href' => '',
  698:                    'text' => 'Analyzing a problem'}];
  699: 
  700:     my $result =
  701:         &Apache::loncommon::start_page('Analyzing a problem',
  702:                                        $js,
  703:                                        {'bread_crumbs' => $brcrum,})
  704:        .&Apache::loncommon::head_subbox(
  705:                 &Apache::loncommon::CSTR_pageheader());
  706:     $result .= 
  707: 	&Apache::lonxml::message_location().'
  708:             <form name="lonhomework" method="post" action="'.
  709: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
  710:             '<input type="hidden" name="problemmode" value="'.
  711:             $env{'form.problemmode'}.'" />'.
  712: 	    &Apache::structuretags::remember_problem_state().'
  713:             <div class="LC_edit_problem_analyze_header">
  714:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
  715:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
  716:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
  717:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
  718:             <hr />
  719:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
  720:             'onclick="javascript:setmode(this.form,'."'view'".')" />
  721:             <hr />
  722:             </div>
  723:             </form>';
  724:     &Apache::lonxml::add_messages(\$result);
  725:     $request->print($result);
  726:     $request->rflush();
  727: }
  728: 
  729: sub analyze_footer {
  730:     my ($request) = @_;
  731:     $request->print(&Apache::loncommon::end_page());
  732:     $request->rflush();
  733: }
  734: 
  735: sub analyze {
  736:     my ($request,$file) = @_;
  737:     &Apache::lonxml::debug("Analyze");
  738:     my $result;
  739:     my %overall;
  740:     my %seedexample;
  741:     my %allparts;
  742:     my $rndseed=$env{'form.rndseed'};
  743:     &analyze_header($request);
  744:     my %prog_state=
  745: 	&Apache::lonhtmlcommon::Create_PrgWin($request,&mt('Analyze Progress'),
  746: 					      &mt('Getting Problem Variants'),
  747: 					      $env{'form.numtoanalyze'},
  748: 					      'inline',undef);
  749:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
  750: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,
  751: 						 &mt('last problem'));
  752: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
  753:         my $thisseed=$i+$rndseed;
  754: 	my $subresult=&Apache::lonnet::ssi($request->uri,
  755: 					   ('grade_target' => 'analyze'),
  756: 					   ('rndseed' => $thisseed));
  757: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
  758: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  759: 	my @parts;
  760: 	if (defined(@{ $analyze{'parts'} })) {
  761: 	    @parts=@{ $analyze{'parts'} };
  762: 	}
  763: 	foreach my $part (@parts) {
  764: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
  765: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
  766: 		$analyze{$part.'.type'} eq 'stringresponse'	||
  767: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
  768: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
  769: 		    my $i=0;
  770: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
  771: 			push( @{ $overall{$part.'.answer'}[$i] },
  772: 			      $answer_part);
  773: 			my $concatanswer= join("\0",@{ $answer_part });
  774: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
  775: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
  776: 			}
  777: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
  778: 			    $thisseed;
  779: 			$i++;
  780: 		    }
  781: 		}
  782: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
  783: 		    my $answer_part = 
  784: 			['<span class="LC_error">'.&mt('Error').'</span>'];
  785: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
  786: 			$thisseed;
  787: 		    push( @{ $overall{$part.'.answer'}[0] },
  788: 			  $answer_part);
  789: 		}
  790: 	    }
  791: 	}
  792:     }
  793:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,
  794: 					  &mt('Analyzing Results'));
  795:     $request->print('<hr />'
  796:                    .'<h3>'
  797:                    .&mt('List of possible answers')
  798:                    .'</h3>'
  799:     );
  800:     foreach my $part (sort(keys(%allparts))) {
  801: 	if (defined(@{ $overall{$part.'.answer'} })) {
  802: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
  803: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
  804:                 $request->print(&Apache::loncommon::start_data_table()
  805:                                .&Apache::loncommon::start_data_table_header_row()
  806:                                .'<th colspan="'.($num_cols+1).'">'
  807:                                .&mt('Part').' '.$part
  808:                 );
  809: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
  810: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
  811: 		}
  812: 		$request->print('</th>'
  813:                                .&Apache::loncommon::end_data_table_header_row()
  814:                 );
  815: 		my %frequency;
  816: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
  817: 		    $frequency{join("\0",@{ $answer })}++;
  818: 		}
  819:                 $request->print(&Apache::loncommon::start_data_table_header_row()
  820:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
  821:                                .'<th>'.&mt('Frequency').'<br />'
  822:                                .'('.&mt('click for example').')</th>'
  823:                                .&Apache::loncommon::end_data_table_header_row()
  824:                 );
  825: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
  826:                     $request->print(&Apache::loncommon::start_data_table_row()
  827:                                    .'<td>'
  828:                                    .join('</td><td>',split("\0",$answer))
  829: 				   .'</td>'
  830:                                    .'<td>'
  831:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
  832: 				   .'</td>'
  833:                                    .&Apache::loncommon::end_data_table_row()
  834:                     );
  835: 		}
  836:                 $request->print(&Apache::loncommon::end_data_table());
  837: 	    }
  838: 	} else {
  839:             $request->print('<p class="LC_warning">'
  840:                            .&mt('Response [_1] is not analyzable at this time.',$part)
  841: 			   .'</p>'
  842:             );
  843: 	}
  844:     }
  845:     if (scalar(keys(%allparts)) == 0 ) {
  846:         $request->print('<p class="LC_warning">'
  847:                        .&mt('Found no analyzable responses in this problem.'
  848:                            .' Currently only Numerical, Formula and String response styles are supported.')
  849:                        .'</p>'
  850:         );
  851:     }
  852:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
  853:     &analyze_footer($request);
  854:     &Apache::lonhomework::showhash(%overall);
  855:     return $result;
  856: }
  857: 
  858: {
  859:     my $show_problem_status;
  860:     sub reset_show_problem_status {
  861: 	undef($show_problem_status);
  862:     }
  863: 
  864:     sub set_show_problem_status {
  865: 	my ($new_status) = @_;
  866: 	$show_problem_status = lc($new_status);
  867:     }
  868: 
  869:     sub hide_problem_status {
  870: 	return ($show_problem_status eq 'no'
  871: 		|| $show_problem_status eq 'no_feedback_ever');
  872:     }
  873: 
  874:     sub show_problem_status {
  875: 	return ($show_problem_status eq 'yes'
  876: 		|| $show_problem_status eq 'answer'
  877: 		|| $show_problem_status eq '');
  878:     }
  879:     
  880:     sub show_some_problem_status {
  881: 	return ($show_problem_status eq 'no');
  882:     }
  883: 
  884:     sub show_no_problem_status {
  885: 	return ($show_problem_status eq 'no_feedback_ever');
  886:     }
  887:   
  888:     sub show_answer_problem_status {
  889: 	return ($show_problem_status eq 'answer');
  890:     }
  891: }
  892: 
  893: sub editxmlmode {
  894:     my ($request,$file) = @_;
  895:     my $result;
  896:     my $problem=&Apache::lonnet::getfile($file);
  897:     if ($problem eq -1) {
  898: 	&Apache::lonxml::error(
  899:             '<b> '
  900:            .&mt('Unable to find [_1]',
  901:                 '<span class="LC_filename">'.$file.'</span>')
  902:            .'</b>');
  903: 
  904: 	$problem='';
  905:     }
  906:     if (defined($env{'form.editxmltext'}) || defined($env{'form.Undo'})) {
  907: 	my $error=&handle_save_or_undo($request,\$problem,
  908: 				       \$env{'form.editxmltext'});
  909: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
  910:     }
  911:     &Apache::lonhomework::showhashsubset(\%env,'^form');
  912:     if ( $env{'form.submitbutton'} eq &mt('Save and View') ) {
  913: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
  914: 	$env{'form.problemmode'}='view';
  915: 	&renderpage($request,$file);
  916:     } else {
  917: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
  918: 	if ($cols > 80) { $cols = 80; }
  919: 	if ($cols < 70) { $cols = 70; }
  920: 	if ($rows < 20) { $rows = 20; }
  921: 	my $js =
  922: 	    &Apache::edit::js_change_detection(). 
  923: 	    &Apache::loncommon::resize_textarea_js().
  924:             &Apache::structuretags::setmode_javascript().
  925:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
  926: 	my $only_body =  ($env{'environment.remote'} eq 'off')? 0 : 1;
  927: 	my $dragmath_button = 
  928:             &Apache::lonhtmlcommon::dragmath_button("LC_editxmltext",1);
  929: 
  930:     # Breadcrumbs
  931:     my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
  932:                    'text' => 'Construction Space'},
  933:                   {'href' => '',
  934:                    'text' => 'Problem Editing'}];
  935: 
  936: 	my $start_page = 
  937: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
  938: 					   {'no_auto_mt_title' => 1,
  939: 					    'only_body'        => $only_body,
  940: 					    'add_entries'      => {
  941: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
  942: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
  943:                                     },
  944:                                                 'bread_crumbs' => $brcrum,
  945: });
  946: 
  947:     $result=$start_page
  948:            .&Apache::loncommon::head_subbox(
  949:                 &Apache::loncommon::CSTR_pageheader());
  950: 	$result.=&renderpage($request,$file,['no_output_web'],1).
  951:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
  952: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
  953: 	    &Apache::structuretags::remember_problem_state().'
  954:             <div class="LC_edit_problem_editxml_header">
  955:               <table class="LC_edit_problem_header_title"><tr><td>
  956:                '.&mt('Problem Editing').&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').'
  957:                 </td><td align="right">
  958:                   '.&Apache::loncommon::helpLatexCheatsheet('Problem_LON-CAPA_Functions','Script Functions').'
  959:                 </td></tr>
  960:               </table>
  961:               <div class="LC_edit_problem_discards">
  962:                 <input type="hidden" name="problemmode" value="editxml" />
  963: 
  964:                 <input type="button" name="submitmode" accesskey="d" value="'.&mt('Discard Edits and View').'" '.
  965:                 'onclick="javascript:setmode(this.form,'."'discard'".')" />
  966:                 <input type="button" '.&Apache::edit::submit_ask_anyway('setmode(this.form,'."'edit'".')').'name="submitmode" accesskey="e" value="'.&mt('Edit').'" />
  967:                 <input type="submit" name="Undo" accesskey="u" value="'.&mt('undo').'" />
  968:                 '.$dragmath_button.'
  969:               </div>
  970:               <div class="LC_edit_problem_saves">
  971:                 <input type="submit" name="submitbutton" accesskey="s" value="'.&mt('Save').'"  />
  972:                 <input type="submit" name="submitbutton" accesskey="v" value="'.&mt('Save and View').'" />
  973:               </div>
  974:               <hr />
  975: 	      '.&Apache::lonxml::message_location().'
  976:             </div>
  977:             '  . '
  978:             <textarea '.&Apache::edit::element_change_detection().
  979: 	              ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" '.
  980: 		      ' name="editxmltext" id="LC_editxmltext">'.
  981: 		      &HTML::Entities::encode($problem,'<>&"').'</textarea>
  982:             <div id="LC_aftertextarea">
  983:             </div>
  984:             </form>'.&Apache::loncommon::end_page();
  985: 	&Apache::lonxml::add_messages(\$result);
  986: 	$request->print($result);
  987:     }
  988:     return '';
  989: }
  990: 
  991: #
  992: #    Render the page in whatever target desired.
  993: #
  994: sub renderpage {
  995:     my ($request,$file,$targets,$return_string) = @_;
  996: 
  997:     my @targets = @{$targets || [&get_target()]};
  998:     &Apache::lonhomework::showhashsubset(\%env,'form.');
  999:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
 1000: 
 1001:     my $overall_result;
 1002:     foreach my $target (@targets) {
 1003: 	# FIXME need to do something intelligent when a problem goes
 1004:         # from viewable to not viewable due to map conditions
 1005: 	#&setuppermissions();
 1006: 	#if (   $Apache::lonhomework::browse ne '2'
 1007: 	#    && $Apache::lonhomework::browse ne 'F' ) {
 1008: 	#    $request->print(" You most likely shouldn't see me.");
 1009: 	#}
 1010: 	#my $t0 = [&gettimeofday()];
 1011: 	my $output=1;
 1012: 	if ($target eq 'no_output_web') {
 1013: 	    $target = 'web'; $output=0;
 1014: 	}
 1015: 	my $problem=&Apache::lonnet::getfile($file);
 1016: 	my $result;
 1017: 	if ($problem eq -1) {
 1018: 	    $problem='';
 1019: 	    my $filename=(split('/',$file))[-1];
 1020: 	    my $error =
 1021: 		"<b> ".&mt('Unable to find [_1]',
 1022: 			   '<span class="LC_filename">'.$filename.'</span>')
 1023: 		."</b>";
 1024: 	    $result.=
 1025: 		&Apache::loncommon::simple_error_page($request,'Not available',
 1026: 						      $error);
 1027: 	    return;
 1028: 	}
 1029: 
 1030: 	my %mystyle;
 1031: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
 1032: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
 1033: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
 1034: 
 1035: 	&Apache::lonxml::debug("Should be parsing now");
 1036: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
 1037: 					     &setup_vars($target),%mystyle);
 1038: 	&finished_parsing();
 1039: 	if (!$output) { $result = ''; }
 1040: 	#$request->print("Result follows:");
 1041: 	if ($target eq 'modified') {
 1042: 	    &handle_save_or_undo($request,\$problem,\$result);
 1043: 	} else {
 1044: 	    if ($target eq 'analyze') {
 1045: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
 1046: 		undef(%Apache::lonhomework::analyze);
 1047: 	    }
 1048: 	    #my $td=&tv_interval($t0);
 1049: 	    #if ( $Apache::lonxml::debug) {
 1050: 	    #$result =~ s:</body>::;
 1051: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
 1052: 	    #}
 1053: #	    $request->print($result);
 1054: 	    $overall_result.=$result;
 1055: #	    $request->rflush();
 1056: 	}
 1057: 	#$request->print(":Result ends");
 1058: 	#my $td=&tv_interval($t0);
 1059:     }
 1060:     if (!$return_string) {
 1061: 	&Apache::lonxml::add_messages(\$overall_result);
 1062: 	$request->print($overall_result);   
 1063: 	$request->rflush();   
 1064:     } else {
 1065: 	return $overall_result;
 1066:     }
 1067: }
 1068: 
 1069: sub finished_parsing {
 1070:     undef($Apache::lonhomework::parsing_a_problem);
 1071:     undef($Apache::lonhomework::parsing_a_task);
 1072: }
 1073: 
 1074: sub get_template_list {
 1075:     my ($extension) = @_;
 1076:     my $result;
 1077:     my @allnames;
 1078:     &Apache::lonxml::debug("Looking for :$extension:");
 1079:     my $glob_extension  = $extension;
 1080:     if ($extension eq 'survey' || $extension eq 'exam') {
 1081: 	$glob_extension = 'problem';
 1082:     }
 1083:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
 1084: 		     '/templates/*.'.$glob_extension);
 1085:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
 1086:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
 1087:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
 1088:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
 1089:     my ($midpoint,$seconddiv,$numfiles);
 1090:     $numfiles = 0;
 1091:     foreach my $file (@files) {
 1092:         next if ($file->[1] !~ /\S/);
 1093:         $numfiles ++;
 1094:     }
 1095:     if ($numfiles > 0) {
 1096:         $result = '<div class="LC_left_float">';
 1097:         $midpoint = int($numfiles/2);
 1098:         if ($numfiles%2) {
 1099:             $midpoint ++;
 1100:         }
 1101:     }
 1102:     my $count = 0;
 1103:     my $currentcategory='';
 1104:     my $first = 1;
 1105:     foreach my $file (@files) {
 1106: 	next if ($file->[1] !~ /\S/);
 1107:         if ($file->[2] ne $currentcategory) {
 1108:            $currentcategory=$file->[2];
 1109:            if ((!$seconddiv) && ($count >= $midpoint)) {
 1110:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
 1111:                $seconddiv = 1;
 1112:            } elsif (!$first) {
 1113:                $result.='</div>'."\n";
 1114:            } else {
 1115:                $first = 0;
 1116:            }
 1117:            $result.= '<div class="LC_Box">'."\n"
 1118:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
 1119:            $count++;
 1120:         }
 1121: 	$result .=
 1122: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
 1123: 	    $file->[1].'</label>';
 1124:         if ($file->[3]) {
 1125:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
 1126:         }
 1127:         my $filename=$file->[0];
 1128:         $filename=~s/^\/home\/httpd\/html//;
 1129:         $result.=' <span class="LC_fontsize_small">'
 1130:                 .'<a href="'.$filename.'" target="sample">'.&mt('Example').'</a>'
 1131:                 .'</span><br />'."\n";
 1132:         $count ++;
 1133:     }
 1134:     if ($numfiles > 0) {
 1135:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
 1136:     }
 1137:     return $result;
 1138: }
 1139: 
 1140: sub newproblem {
 1141:     my ($request) = @_;
 1142: 
 1143:     if ($env{'form.template'}) {
 1144: 	my $file = $env{'form.template'};
 1145: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1146: 	&File::Copy::copy($file,$dest);
 1147: 	&renderpage($request,$dest);
 1148: 	return;
 1149:     }
 1150: 
 1151:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
 1152:     &Apache::lonxml::debug("Looking for :$extension:");
 1153:     my $templatelist=&get_template_list($extension);
 1154:     if ($env{'form.newfile'} && !$templatelist) {
 1155: 	# no templates found
 1156: 	my $templatefilename =
 1157: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
 1158: 	&Apache::lonxml::debug("$templatefilename");
 1159: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1160: 	&File::Copy::copy($templatefilename,$dest);
 1161: 	&renderpage($request,$dest);
 1162:     } else {
 1163: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
 1164: 	my $shownurl=$url;	
 1165: 	$shownurl=~s-^/~-/priv/-;
 1166: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
 1167: 	my $errormsg;
 1168: 	my $instructions;
 1169:         my $brcrum = [{'href' => &Apache::loncommon::authorspace(),
 1170:                        'text' => 'Construction Space'},
 1171:                       {'href' => '',
 1172:                        'text' => "Create New $extension"}];
 1173: 	my $start_page = 
 1174:             &Apache::loncommon::start_page("Create New $extension",
 1175:                                            undef,
 1176:                                            {'bread_crumbs' => $brcrum,});
 1177: 	$request->print(
 1178:         $start_page
 1179:        .&Apache::loncommon::head_subbox(
 1180:                 &Apache::loncommon::CSTR_pageheader())
 1181:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
 1182: $errormsg
 1183: ".&mt("The requested file [_1] currently does not exist.",
 1184:       '<span class="LC_filename">'.$shownurl.'</span>').'
 1185: <p class="LC_info">
 1186: '.&mt("To create a new $extension, select a template from the".
 1187:       " list below. Then click on the \"Create $extension\" button.").'
 1188: </p><div><form action="'.$url.'" method="post">');
 1189: 
 1190: 	if (defined($templatelist)) {
 1191: 	    $request->print($templatelist);
 1192: 	}
 1193: 	$request->print('<br /><input type="submit" name="newfile" value="'.
 1194: 			&mt("Create $extension").'" />');
 1195: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
 1196:     }
 1197:     return;
 1198: }
 1199: 
 1200: sub update_construct_style {
 1201:     if ($env{'request.state'} eq "construct"
 1202: 	&& $env{'form.problemmode'} eq 'view' 
 1203: 	&&  defined($env{'form.submitted'})
 1204: 	&& !defined($env{'form.resetdata'})
 1205: 	&& !defined($env{'form.newrandomization'})) {
 1206: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
 1207: 	    ||$env{'form.clear_style_file'}) {
 1208: 	    &Apache::lonnet::delenv('construct.style');
 1209: 	} elsif ($env{'form.style_file'} 
 1210: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
 1211: 	    &Apache::lonnet::appenv({'construct.style' => 
 1212: 				        $env{'form.style_file'}});
 1213: 	}
 1214:     }
 1215: }
 1216: 
 1217: 
 1218: sub handler {
 1219:     #my $t0 = [&gettimeofday()];
 1220:     my $request=$_[0];
 1221:     $Apache::lonxml::request=$request;
 1222:     $Apache::lonxml::debug=$env{'user.debug'};
 1223:     $env{'request.uri'}=$request->uri;
 1224:     &setuppermissions();
 1225: 
 1226:     my $file=&Apache::lonnet::filelocation("",$request->uri);
 1227: 
 1228:     #check if we know where we are
 1229:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread()) { 
 1230: 	# if we are browsing we might not be able to know where we are
 1231: 	if ($Apache::lonhomework::browse ne 'F' && 
 1232: 	    $env{'request.state'} ne "construct") {
 1233: 	    #should know where we are, so ask
 1234: 	    &unset_permissions();
 1235: 	    $request->internal_redirect('/adm/ambiguous');
 1236: 	    return OK;
 1237: 	}
 1238:     }
 1239:     if (&setupheader($request)) {
 1240: 	&unset_permissions();
 1241: 	return OK;
 1242:     }
 1243:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
 1244:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
 1245:     my ($symb) = &Apache::lonnet::whichuser();
 1246:     &Apache::lonxml::debug('symb is '.$symb);
 1247:     if ($env{'request.state'} eq "construct") {
 1248: 	if ( -e $file ) {
 1249: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1250: 						    ['problemmode']);
 1251: 	    if (!(defined $env{'form.problemmode'})) {
 1252: 		#first visit to problem in construction space
 1253: 		$env{'form.problemmode'}= 'view';
 1254: 		&renderpage($request,$file);
 1255: 	    } elsif ($env{'form.problemmode'} eq 'editxml') {
 1256: 		&editxmlmode($request,$file);
 1257: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
 1258: 		&analyze($request,$file);
 1259: 	    } else {
 1260: 		&update_construct_style();
 1261: 		&renderpage($request,$file);
 1262: 	    }
 1263: 	} else {
 1264: 	    # requested file doesn't exist in contruction space
 1265: 	    &newproblem($request);
 1266: 	}
 1267:     } else {
 1268: 	# just render the page normally outside of construction space
 1269: 	&Apache::lonxml::debug("not construct");
 1270: 	&renderpage($request,$file);
 1271:     }
 1272:     #my $td=&tv_interval($t0);
 1273:     #&Apache::lonxml::debug("Spent $td seconds processing");
 1274:     # always turn off debug messages
 1275:     $Apache::lonxml::debug=0;
 1276:     &unset_permissions();
 1277:     return OK;
 1278: 
 1279: }
 1280: 
 1281: 1;
 1282: __END__

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