File:  [LON-CAPA] / loncom / homework / lonhomework.pm
Revision 1.271: download - view: text, annotated - select for diffs
Fri Aug 24 21:13:53 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- removing useless line

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

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