File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.329: download - view: text, annotated - select for diffs
Mon Oct 31 19:35:03 2011 UTC (12 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 1320.
- Use lonDocRoot perlvar in place of static string: '/home/httpd/html'.

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

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