File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.317.4.1: download - view: text, annotated - select for diffs
Fri Aug 13 01:33:48 2010 UTC (13 years, 8 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0_RC1
Diff to branchpoint 1.317: preferred, unified
- Backport 1.320.

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

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