Annotation of loncom/homework/lonhomework.pm, revision 1.356

1.63      albertel    1: # The LearningOnline Network with CAPA
1.52      albertel    2: # The LON-CAPA Homework handler
1.63      albertel    3: #
1.356   ! raeburn     4: # $Id: lonhomework.pm,v 1.355 2015/06/29 15:42:07 damieng Exp $
1.63      albertel    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/
1.159     www        27: 
1.1       albertel   28: 
                     29: package Apache::lonhomework;
                     30: use strict;
1.73      albertel   31: use Apache::style();
                     32: use Apache::lonxml();
1.204     albertel   33: use Apache::lonnet;
1.73      albertel   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();
1.83      albertel   41: use Apache::caparesponse();
                     42: use Apache::radiobuttonresponse();
                     43: use Apache::optionresponse();
                     44: use Apache::imageresponse();
                     45: use Apache::essayresponse();
                     46: use Apache::externalresponse();
1.106     albertel   47: use Apache::rankresponse();
1.107     albertel   48: use Apache::matchresponse();
1.137     albertel   49: use Apache::chemresponse();
1.321     www        50: use Apache::functionplotresponse();
1.169     albertel   51: use Apache::drawimage();
1.355     damieng    52: use Apache::loncapamath();
1.26      www        53: use Apache::Constants qw(:common);
1.83      albertel   54: use Apache::loncommon();
1.354     musolffc   55: use Apache::lonparmset();
1.146     albertel   56: use Apache::lonlocal;
1.179     albertel   57: use Time::HiRes qw( gettimeofday tv_interval );
1.282     albertel   58: use HTML::Entities();
                     59: use File::Copy();
1.188     foxr       60: 
1.189     albertel   61: # FIXME - improve commenting
1.188     foxr       62: 
1.43      albertel   63: 
1.69      harris41   64: BEGIN {
1.145     albertel   65:     &Apache::lonxml::register_insert();
1.43      albertel   66: }
                     67: 
1.188     foxr       68: 
1.276     foxr       69: =pod
                     70: 
                     71: =item set_bubble_lines()
                     72: 
                     73: Called at analysis time to set the bubble lines
                     74: hash for the problem.. This should be called in the
                     75: end_problemtype tag in analysis mode.
                     76: 
                     77: We fetch the hash of part id counters from lonxml
                     78:     and push them into analyze:{part_id.bubble_lines}.
                     79: 
                     80: =cut
                     81: 
                     82: sub set_bubble_lines {
                     83:     my %bubble_counters = &Apache::lonxml::get_bubble_line_hash();
                     84: 
                     85:     foreach my $key (keys(%bubble_counters)) {
                     86: 	$Apache::lonhomework::analyze{"$key.bubble_lines"} =
                     87: 	    $bubble_counters{"$key"};
                     88:     }
                     89: }
                     90: 
1.301     jms        91: #
                     92: # Decides what targets to render for.
                     93: # Implicit inputs:
                     94: #   Various session environment variables:
                     95: #      request.state -  published  - is a /res/ resource
                     96: #                       uploaded   - is a /uploaded/ resource
                     97: #                       contruct   - is a /priv/ resource
                     98: #      form.grade_target - a form parameter requesting a specific target
1.5       albertel   99: sub get_target {
1.204     albertel  100:     &Apache::lonxml::debug("request.state = $env{'request.state'}");
                    101:     if( defined($env{'form.grade_target'})) {
                    102: 	&Apache::lonxml::debug("form.grade_target= $env{'form.grade_target'}");
1.188     foxr      103:     } else {
1.189     albertel  104: 	&Apache::lonxml::debug("form.grade_target <undefined>");
1.188     foxr      105:     }
1.204     albertel  106:     if (($env{'request.state'} eq "published") ||
                    107: 	($env{'request.state'} eq "uploaded")) {
                    108: 	if ( defined($env{'form.grade_target'}  ) 
                    109: 	     && ($env{'form.grade_target'} eq 'tex')) {
                    110: 	    return ($env{'form.grade_target'});
                    111: 	} elsif ( defined($env{'form.grade_target'}  ) 
1.145     albertel  112: 		  && ($Apache::lonhomework::viewgrades eq 'F' )) {
1.207     albertel  113: 	    return ($env{'form.grade_target'});
1.244     albertel  114: 	} elsif ( $env{'form.grade_target'} eq 'webgrade'
                    115: 		  && ($Apache::lonhomework::queuegrade eq 'F' )) {
                    116: 	    return ($env{'form.grade_target'});
1.320     raeburn   117: 	} elsif ($env{'form.grade_target'} eq 'answer') {
                    118:             if ($env{'form.answer_output_mode'} eq 'tex') {
                    119:                 return ($env{'form.grade_target'});
                    120:             }
                    121:         }
1.207     albertel  122: 	if ($env{'form.webgrade'} &&
1.244     albertel  123: 	    ($Apache::lonhomework::modifygrades eq 'F'
                    124: 	     || $Apache::lonhomework::queuegrade eq 'F' )) {
1.207     albertel  125: 	    return ('grade','webgrade');
1.145     albertel  126: 	}
1.204     albertel  127: 	if ( defined($env{'form.submitted'}) &&
                    128: 	     ( !defined($env{'form.newrandomization'}))) {
1.217     albertel  129: 	    return ('grade', 'web');
1.145     albertel  130: 	} else {
1.217     albertel  131: 	    return ('web');
1.145     albertel  132: 	}
1.204     albertel  133:     } elsif ($env{'request.state'} eq "construct") {
1.323     www       134: #
                    135: # We are in construction space, editing and testing problems
                    136: #
1.204     albertel  137: 	if ( defined($env{'form.grade_target'}) ) {
                    138: 	    return ($env{'form.grade_target'});
1.145     albertel  139: 	}
1.204     albertel  140: 	if ( defined($env{'form.preview'})) {
                    141: 	    if ( defined($env{'form.submitted'})) {
1.323     www       142: #
                    143: # We are doing a problem preview
                    144: #
1.145     albertel  145: 		return ('grade', 'web');
                    146: 	    } else {
                    147: 		return ('web');
                    148: 	    }
                    149: 	} else {
1.267     albertel  150: 	    if ($env{'form.problemstate'} eq 'WEB_GRADE') {
                    151: 		return ('grade','webgrade','answer');
1.324     www       152:             } elsif ($env{'form.problemmode'} eq 'view') {
                    153:                 return ('grade','web','answer');
1.323     www       154: 	    } elsif ($env{'form.problemmode'} eq 'saveview') {
                    155:                 return ('modified','web','answer');
                    156:             } elsif ($env{'form.problemmode'} eq 'discard') {
                    157:                 return ('web','answer');
                    158:             } elsif (($env{'form.problemmode'} eq 'saveedit') ||
                    159:                      ($env{'form.problemmode'} eq 'undo')) {
                    160:                 return ('modified','no_output_web','edit');
                    161:             } elsif ($env{'form.problemmode'} eq 'edit') {
                    162: 		return ('no_output_web','edit');
1.145     albertel  163: 	    } else {
                    164: 		return ('web');
                    165: 	    }
1.323     www       166:         }
                    167: #
1.338     raeburn   168: # End of Authoring Space
1.323     www       169: #
1.15      albertel  170:     }
1.323     www       171: #
                    172: # Huh? We are nowhere, so do nothing.
                    173: #
1.145     albertel  174:     return ();
1.5       albertel  175: }
                    176: 
1.3       albertel  177: sub setup_vars {
1.145     albertel  178:     my ($target) = @_;
                    179:     return ';'
1.11      albertel  180: #  return ';$external::target='.$target.';';
1.2       albertel  181: }
                    182: 
1.200     albertel  183: sub proctor_checked_in {
1.226     albertel  184:     my ($slot_name,$slot,$type)=@_;
                    185:     my @possible_proctors=split(",",$slot->{'proctor'});
                    186:     
1.248     albertel  187:     return 1 if (!@possible_proctors);
                    188: 
1.226     albertel  189:     my $key;
                    190:     if ($type eq 'Task') {
1.230     albertel  191: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
                    192: 	$key ="resource.$version.0.checkedin";
1.226     albertel  193:     } elsif ($type eq 'problem') {
                    194: 	$key ='resource.0.checkedin';
                    195:     }
1.249     albertel  196:     # backward compatability, used to be username@domain, 
                    197:     # now is username:domain
                    198:     my $who = $Apache::lonhomework::history{$key};
                    199:     if ($who !~ /:/) {
                    200: 	$who =~ tr/@/:/;
                    201:     }     
1.226     albertel  202:     foreach my $possible (@possible_proctors) { 
1.249     albertel  203: 	if ($who eq $possible
1.226     albertel  204: 	    && $Apache::lonhomework::history{$key.'.slot'} eq $slot_name) {
1.202     albertel  205: 	    return 1;
                    206: 	}
                    207:     }
1.226     albertel  208:     
1.200     albertel  209:     return 0;
                    210: }
                    211: 
1.226     albertel  212: sub check_slot_access {
1.356   ! raeburn   213:     my ($id,$type,$symb)=@_;
1.226     albertel  214: 
1.207     albertel  215:     # does it pass normal muster
1.356   ! raeburn   216:     my ($status,$datemsg)=&check_access($id,$symb);
1.226     albertel  217:     
1.356   ! raeburn   218:     my $useslots = &Apache::lonnet::EXT("resource.0.useslots",$symb);
1.251     albertel  219:     if ($useslots ne 'resource' && $useslots ne 'map' 
                    220: 	&& $useslots ne 'map_map') {
1.226     albertel  221: 	return ($status,$datemsg);
                    222:     }
                    223: 
1.200     albertel  224:     if ($status eq 'SHOW_ANSWER' ||
                    225: 	$status eq 'CLOSED' ||
                    226: 	$status eq 'INVALID_ACCESS' ||
                    227: 	$status eq 'UNAVAILABLE') {
                    228: 	return ($status,$datemsg);
                    229:     }
1.204     albertel  230:     if ($env{'request.state'} eq "construct") {
1.203     albertel  231: 	return ($status,$datemsg);
                    232:     }
1.226     albertel  233:     
                    234:     if ($type eq 'Task') {
                    235: 	my $version=$Apache::lonhomework::history{'resource.version'};
1.230     albertel  236: 	if ($Apache::lonhomework::history{"resource.$version.0.checkedin"} &&
                    237: 	    $Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass') {
1.226     albertel  238: 	    return ('SHOW_ANSWER');
                    239: 	}
1.207     albertel  240:     }
1.226     albertel  241: 
1.356   ! raeburn   242:     my $availablestudent = &Apache::lonnet::EXT("resource.0.availablestudent",$symb);
        !           243:     my $available = &Apache::lonnet::EXT("resource.0.available",$symb);
1.288     raeburn   244:     my @slots= (split(':',$availablestudent),split(':',$available));
1.210     albertel  245: 
1.200     albertel  246: #    if (!@slots) {
                    247: #	return ($status,$datemsg);
                    248: #    }
                    249:     my $slotstatus='NOT_IN_A_SLOT';
1.206     albertel  250:     my ($returned_slot,$slot_name);
1.334     raeburn   251:     my $now = time;
                    252:     my $num_usable_slots = 0;
1.210     albertel  253:     foreach my $slot (@slots) {
1.241     albertel  254: 	$slot =~ s/(^\s*|\s*$)//g;
1.201     albertel  255: 	&Apache::lonxml::debug("getting $slot");
1.200     albertel  256: 	my %slot=&Apache::lonnet::get_slot($slot);
1.201     albertel  257: 	&Apache::lonhomework::showhash(%slot);
1.334     raeburn   258:         next if ($slot{'endtime'} < $now);
                    259:         $num_usable_slots ++;
                    260: 	if ($slot{'starttime'} < $now &&
                    261: 	    $slot{'endtime'} > $now &&
1.297     raeburn   262: 	    &Apache::loncommon::check_ip_acc($slot{'ip'})) {
1.202     albertel  263: 	    &Apache::lonxml::debug("$slot is good");
                    264: 	    $slotstatus='NEEDS_CHECKIN';
                    265: 	    $returned_slot=\%slot;
1.206     albertel  266: 	    $slot_name=$slot;
1.200     albertel  267: 	    last;
1.334     raeburn   268:         } 
1.200     albertel  269:     }
1.202     albertel  270:     if ($slotstatus eq 'NEEDS_CHECKIN' &&
1.226     albertel  271: 	&proctor_checked_in($slot_name,$returned_slot,$type)) {
1.322     raeburn   272: 	&Apache::lonxml::debug("proctor checked in");
                    273: 	$slotstatus=$status;
1.200     albertel  274:     }
1.226     albertel  275: 
1.235     albertel  276:     my ($is_correct,$got_grade,$checkedin);
1.226     albertel  277:     if ($type eq 'Task') {
1.230     albertel  278: 	my $version=$Apache::lonhomework::history{'resource.0.version'};
1.231     albertel  279: 	$got_grade = 
                    280: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} 
                    281: 	     =~ /^(?:pass|fail)$/);
1.235     albertel  282: 	$is_correct =  
                    283: 	    ($Apache::lonhomework::history{"resource.$version.0.status"} eq 'pass'
                    284: 	     || $Apache::lonhomework::history{"resource.0.solved"} =~ /^correct_/ );
1.226     albertel  285: 	$checkedin =
1.230     albertel  286: 	    $Apache::lonhomework::history{"resource.$version.0.checkedin"};
1.226     albertel  287:     } elsif ($type eq 'problem') {
1.252     albertel  288: 	$got_grade  = 1;
                    289: 	$checkedin  = $Apache::lonhomework::history{"resource.0.checkedin"};
                    290: 	$is_correct =
                    291: 	    ($Apache::lonhomework::history{"resource.0.solved"} =~/^correct_/);
1.226     albertel  292:     }
                    293:     
1.235     albertel  294:     &Apache::lonxml::debug(" slot is $slotstatus checkedin ($checkedin) got_grade ($got_grade) is_correct ($is_correct)");
                    295:     
1.243     albertel  296:     # no slot is currently open, and has been checked in for this version
                    297:     # but hasn't got a grade, therefore must be awaiting a grade
                    298:     if (!defined($slot_name)
                    299: 	&& $checkedin 
1.236     albertel  300: 	&& !$got_grade) {
                    301: 	return ('WAITING_FOR_GRADE');
                    302:     }
                    303: 
1.309     raeburn   304:     # Previously used slot is no longer open, and has been checked in for this version.
                    305:     # However, the problem is not closed, and potentially, another slot might be
                    306:     # used to gain access to it to work on it, until the due date is reached, and the
                    307:     # problem then becomes CLOSED.  Therefore return the slotstatus - 
1.334     raeburn   308:     # (which will be one of: NOT_IN_A_SLOT, RESERVABLE, RESERVABLE_LATER, or NOTRESERVABLE.
                    309:     if (!defined($slot_name) && $type eq 'problem') {
                    310:         if ($slotstatus eq 'NOT_IN_A_SLOT') {
                    311:             if (!$num_usable_slots) {
                    312:                 if ($env{'request.course.id'}) {
                    313:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    314:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.356   ! raeburn   315:                     unless ($symb) {
        !           316:                         ($symb)=&Apache::lonnet::whichuser();
        !           317:                     }
1.334     raeburn   318:                     $slotstatus = 'NOTRESERVABLE';
                    319:                     my ($reservable_now_order,$reservable_now,$reservable_future_order,
                    320:                         $reservable_future) = 
                    321:                         &Apache::loncommon::get_future_slots($cnum,$cdom,$now,$symb);
                    322:                     if ((ref($reservable_now_order) eq 'ARRAY') && (ref($reservable_now) eq 'HASH')) {
                    323:                         if (@{$reservable_now_order} > 0) {
                    324:                             $slotstatus = 'RESERVABLE';
                    325:                             $datemsg = $reservable_now->{$reservable_now_order->[-1]}{'endreserve'};
                    326:                         }
                    327:                     }
                    328:                     unless ($slotstatus eq 'RESERVABLE') {
                    329:                         if ((ref($reservable_future_order) eq 'ARRAY') && (ref($reservable_future) eq 'HASH')) {
                    330:                             if (@{$reservable_future_order} > 0) {
                    331:                                 $slotstatus = 'RESERVABLE_LATER';
                    332:                                 $datemsg = $reservable_future->{$reservable_future_order->[0]}{'startreserve'};
                    333:                             }
                    334:                         }
                    335:                     }
                    336:                 }
                    337:             }
                    338:         }
                    339:         return ($slotstatus,$datemsg);
1.252     albertel  340:     }
                    341: 
1.226     albertel  342:     if ($slotstatus eq 'NOT_IN_A_SLOT' 
                    343: 	&& $checkedin ) {
                    344: 
1.231     albertel  345: 	if ($got_grade) {
1.209     albertel  346: 	    return ('SHOW_ANSWER');
                    347: 	} else {
                    348: 	    return ('WAITING_FOR_GRADE');
                    349: 	}
1.226     albertel  350: 
1.207     albertel  351:     }
1.255     albertel  352: 
1.235     albertel  353:     if ( $is_correct) {
1.255     albertel  354: 	if ($type eq 'problem') {
                    355: 	    return ($status);
                    356: 	}
1.235     albertel  357: 	return ('SHOW_ANSWER');
                    358:     }
1.255     albertel  359: 
1.225     albertel  360:     if ( $status eq 'CANNOT_ANSWER' && 
                    361: 	 ($slotstatus ne 'NEEDS_CHECKIN' && $slotstatus ne 'NOT_IN_A_SLOT')) {
                    362: 	return ($status,$datemsg);
                    363:     }
                    364: 
1.206     albertel  365:     return ($slotstatus,$datemsg,$slot_name,$returned_slot);
1.198     albertel  366: }
1.200     albertel  367: 
1.301     jms       368: # JB, 9/24/2002: Any changes in this function may require a change
                    369: # in lonnavmaps::resource::getDateStatus.
1.53      www       370: sub check_access {
1.356   ! raeburn   371:     my ($id,$symb) = @_;
1.145     albertel  372:     my $date ='';
                    373:     my $status;
                    374:     my $datemsg = '';
                    375:     my $lastdate = '';
                    376:     my $type;
                    377:     my $passed;
                    378: 
1.204     albertel  379:     if ($env{'request.state'} eq "construct") {
                    380: 	if ($env{'form.problemstate'}) {
                    381: 	    if ($env{'form.problemstate'} =~ /^CANNOT_ANSWER/) {
1.277     albertel  382: 		if ( ! ($env{'form.problemstate'} eq 'CANNOT_ANSWER_correct' 
                    383: 			&& &hide_problem_status())) {
1.168     albertel  384: 		    return ('CANNOT_ANSWER',
1.174     www       385: 			    &mt('is in this state due to author settings.'));
1.167     albertel  386: 		}
1.165     albertel  387: 	    } else {
1.204     albertel  388: 		return ($env{'form.problemstate'},
1.174     www       389: 			&mt('is in this state due to author settings.'));
1.165     albertel  390: 	    }
                    391: 	}
1.145     albertel  392: 	&Apache::lonxml::debug("in construction ignoring dates");
                    393: 	$status='CAN_ANSWER';
1.146     albertel  394: 	$datemsg=&mt('is in under construction');
1.163     albertel  395: #	return ($status,$datemsg);
1.145     albertel  396:     }
                    397: 
                    398:     &Apache::lonxml::debug("checking for part :$id:");
                    399:     &Apache::lonxml::debug("time:".time);
1.152     albertel  400: 
1.356   ! raeburn   401:     unless ($symb) {
        !           402:         ($symb)=&Apache::lonnet::whichuser();
        !           403:     }
1.212     albertel  404:     &Apache::lonxml::debug("symb:".$symb);
                    405:     #if ($env{'request.state'} ne "construct" && $symb ne '') {
1.204     albertel  406:     if ($env{'request.state'} ne "construct") {
1.356   ! raeburn   407:         my $idacc = &Apache::lonnet::EXT("resource.$id.acc",$symb);
1.297     raeburn   408: 	my $allowed=&Apache::loncommon::check_ip_acc($idacc);
1.163     albertel  409: 	if (!$allowed && ($Apache::lonhomework::browse ne 'F')) {
                    410: 	    $status='INVALID_ACCESS';
                    411: 	    $date=&mt("can not be accessed from your location.");
1.145     albertel  412: 	    return($status,$date);
                    413: 	}
1.327     raeburn   414: 	if ($env{'form.grade_imsexport'}) {
                    415:             if (($env{'request.course.id'}) && 
                    416:                 (&Apache::lonnet::allowed('mdc',$env{'request.course.id'}))) {
                    417:                 return ('SHOW_ANSWER');
                    418:             }
                    419:         }
1.226     albertel  420: 	foreach my $temp ("opendate","duedate","answerdate") {
1.163     albertel  421: 	    $lastdate = $date;
1.247     albertel  422: 	    if ($temp eq 'duedate') {
1.356   ! raeburn   423: 		$date = &due_date($id,$symb);
1.247     albertel  424: 	    } else {
1.356   ! raeburn   425: 		$date = &Apache::lonnet::EXT("resource.$id.$temp",$symb);
1.247     albertel  426: 	    }
                    427: 	    
1.356   ! raeburn   428: 	    my $thistype = &Apache::lonnet::EXT("resource.$id.$temp.type",$symb);
1.163     albertel  429: 	    if ($thistype =~ /^(con_lost|no_such_host)/ ||
                    430: 		$date     =~ /^(con_lost|no_such_host)/) {
                    431: 		$status='UNAVAILABLE';
                    432: 		$date=&mt("may open later.");
                    433: 		return($status,$date);
                    434: 	    }
                    435: 	    if ($thistype eq 'date_interval') {
                    436: 		if ($temp eq 'opendate') {
1.356   ! raeburn   437: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)-$date;
1.163     albertel  438: 		}
                    439: 		if ($temp eq 'answerdate') {
1.356   ! raeburn   440: 		    $date=&Apache::lonnet::EXT("resource.$id.duedate",$symb)+$date;
1.163     albertel  441: 		}
1.145     albertel  442: 	    }
1.163     albertel  443: 	    &Apache::lonxml::debug("found :$date: for :$temp:");
                    444: 	    if ($date eq '') {
                    445: 		$date = &mt("an unknown date"); $passed = 0;
                    446: 	    } elsif ($date eq 'con_lost') {
                    447: 		$date = &mt("an indeterminate date"); $passed = 0;
                    448: 	    } else {
                    449: 		if (time < $date) { $passed = 0; } else { $passed = 1; }
1.274     www       450: 		$date = &Apache::lonlocal::locallocaltime($date);
1.145     albertel  451: 	    }
1.163     albertel  452: 	    if (!$passed) { $type=$temp; last; }
1.145     albertel  453: 	}
1.163     albertel  454: 	&Apache::lonxml::debug("have :$type:$passed:");
                    455: 	if ($passed) {
                    456: 	    $status='SHOW_ANSWER';
                    457: 	    $datemsg=$date;
                    458: 	} elsif ($type eq 'opendate') {
                    459: 	    $status='CLOSED';
1.343     bisitz    460: 	    $datemsg = &mt('will open on [_1]',$date);
1.163     albertel  461: 	} elsif ($type eq 'duedate') {
                    462: 	    $status='CAN_ANSWER';
1.343     bisitz    463: 	    $datemsg = &mt('is due at [_1]',$date);
1.163     albertel  464: 	} elsif ($type eq 'answerdate') {
                    465: 	    $status='CLOSED';
1.343     bisitz    466: 	    $datemsg = &mt('was due on [_1], and answers will be available on [_2]',
                    467:                                $lastdate,$date);
1.145     albertel  468: 	}
                    469:     }
1.212     albertel  470:     if ($status eq 'CAN_ANSWER' ||
                    471: 	(($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED'))) {
1.145     albertel  472: 	#check #tries, and if correct.
                    473: 	my $tries = $Apache::lonhomework::history{"resource.$id.tries"};
1.356   ! raeburn   474: 	my $maxtries = &Apache::lonnet::EXT("resource.$id.maxtries",$symb);
1.145     albertel  475: 	if ( $tries eq '' ) { $tries = '0'; }
1.164     albertel  476: 	if ( $maxtries eq '' && 
1.204     albertel  477: 	     $env{'request.state'} ne 'construct') { $maxtries = '2'; } 
1.164     albertel  478: 	if ($maxtries && $tries >= $maxtries) { $status = 'CANNOT_ANSWER'; }
1.145     albertel  479: 	# if (correct and show prob status) or excused then CANNOT_ANSWER
1.331     raeburn   480: 	if ( ($Apache::lonhomework::history{"resource.$id.solved"}=~/^correct/)
                    481: 	      && (&show_problem_status()) ) {
1.333     raeburn   482:             if (($Apache::lonhomework::history{"resource.$id.awarded"} >= 1) ||
1.356   ! raeburn   483:                 (&Apache::lonnet::EXT("resource.$id.retrypartial",$symb) !~/^1|on|yes$/i)) {
1.331     raeburn   484: 	        $status = 'CANNOT_ANSWER';
                    485:             }
                    486:         } elsif ($Apache::lonhomework::history{"resource.$id.solved"}=~/^excused/) {
1.145     albertel  487: 	    $status = 'CANNOT_ANSWER';
                    488: 	}
1.285     albertel  489: 	if ($status eq 'CANNOT_ANSWER'
                    490: 	    && &show_answer_problem_status()) {
                    491: 	    $status = 'SHOW_ANSWER';
                    492: 	}
1.121     albertel  493:     }
1.181     albertel  494:     if ($status eq 'CAN_ANSWER' || $status eq 'CANNOT_ANSWER') {
1.356   ! raeburn   495: 	my @interval=&Apache::lonnet::EXT("resource.$id.interval",$symb);
1.286     albertel  496: 	&Apache::lonxml::debug("looking for interval @interval");
                    497: 	if ($interval[0]) {
1.356   ! raeburn   498: 	    my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
1.177     albertel  499: 	    &Apache::lonxml::debug("looking for accesstime $first_access");
                    500: 	    if (!$first_access) {
                    501: 		$status='NOT_YET_VIEWED';
1.356   ! raeburn   502: 		my $due_date = &due_date($id,$symb);
1.256     albertel  503: 		my $seconds_left = $due_date - time;
1.286     albertel  504: 		if ($seconds_left > $interval[0] || $due_date eq '') {
                    505: 		    $seconds_left = $interval[0];
1.256     albertel  506: 		}
                    507: 		$datemsg=&seconds_to_human_length($seconds_left);
1.177     albertel  508: 	    }
                    509: 	}
                    510:     }
1.247     albertel  511: 
1.133     albertel  512:   #if (($status ne 'CLOSED') && ($Apache::lonhomework::type eq 'exam') &&
                    513:   #    (!$Apache::lonhomework::history{"resource.0.outtoken"})) {
                    514:   #    return ('UNCHECKEDOUT','needs to be checked out');
                    515:   #}
1.54      www       516: 
1.145     albertel  517:     &Apache::lonxml::debug("sending back :$status:$datemsg:");
                    518:     if (($Apache::lonhomework::browse eq 'F') && ($status eq 'CLOSED')) {
                    519: 	&Apache::lonxml::debug("should be allowed to browse a resource when closed");
                    520: 	$status='CAN_ANSWER';
1.146     albertel  521: 	$datemsg=&mt('is closed but you are allowed to view it');
1.145     albertel  522:     }
1.106     albertel  523: 
1.145     albertel  524:     return ($status,$datemsg);
1.20      albertel  525: }
1.301     jms       526: # this should work exactly like the copy in lonnavmaps.pm
1.246     albertel  527: sub due_date {
1.250     albertel  528:     my ($part_id,$symb,$udom,$uname)=@_;
1.246     albertel  529:     my $date;
1.286     albertel  530:     my @interval= &Apache::lonnet::EXT("resource.$part_id.interval",$symb,
1.250     albertel  531: 				       $udom,$uname);
1.286     albertel  532:     &Apache::lonxml::debug("looking for interval $part_id $symb @interval");
1.250     albertel  533:     my $due_date= &Apache::lonnet::EXT("resource.$part_id.duedate",$symb,
                    534: 				       $udom,$uname);
1.247     albertel  535:     &Apache::lonxml::debug("looking for due_date $part_id $symb $due_date");
1.286     albertel  536:     if ($interval[0] =~ /\d+/) {
                    537: 	my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
                    538: 	&Apache::lonxml::debug("looking for first_access $first_access ($interval[1])");
1.247     albertel  539: 	if (defined($first_access)) {
1.286     albertel  540: 	    my $interval = $first_access+$interval[0];
1.283     albertel  541: 	    $date = (!$due_date || $interval < $due_date) ? $interval
                    542:                                                           : $due_date;
1.247     albertel  543: 	} else {
                    544: 	    $date = $due_date;
                    545: 	}
                    546:     } else {
                    547: 	$date = $due_date;
1.246     albertel  548:     }
1.345     musolffc  549:     return $date;
1.246     albertel  550: }
                    551: 
1.192     albertel  552: sub seconds_to_human_length {
                    553:     my ($length)=@_;
                    554: 
                    555:     my $seconds=$length%60; $length=int($length/60);
                    556:     my $minutes=$length%60; $length=int($length/60);
                    557:     my $hours=$length%24;   $length=int($length/24);
                    558:     my $days=$length;
                    559: 
                    560:     my $timestr;
                    561:     if ($days > 0) { $timestr.=&mt('[quant,_1,day]',$days); }
                    562:     if ($hours > 0) { $timestr.=($timestr?", ":"").
                    563: 			  &mt('[quant,_1,hour]',$hours); }
                    564:     if ($minutes > 0) { $timestr.=($timestr?", ":"").
                    565: 			    &mt('[quant,_1,minute]',$minutes); }
                    566:     if ($seconds > 0) { $timestr.=($timestr?", ":"").
                    567: 			    &mt('[quant,_1,second]',$seconds); }
                    568:     return $timestr;
                    569: }
                    570: 
1.41      albertel  571: sub showhash {
1.145     albertel  572:     my (%hash) = @_;
                    573:     &showhashsubset(\%hash,'.');
                    574:     return '';
1.79      albertel  575: }
                    576: 
1.106     albertel  577: sub showarray {
                    578:     my ($array)=@_;
                    579:     my $string="(";
                    580:     foreach my $elm (@{ $array }) {
1.193     albertel  581: 	if (ref($elm) eq 'ARRAY') {
                    582: 	    $string.=&showarray($elm);
                    583: 	} elsif (ref($elm) eq 'HASH') {
                    584: 	    $string.= "HASH --- \n<br />";
                    585: 	    $string.= &showhashsubset($elm,'.');
1.106     albertel  586: 	} else {
                    587: 	    $string.="$elm,"
                    588: 	}
                    589:     }
                    590:     chop($string);
                    591:     $string.=")";
                    592:     return $string;
                    593: }
                    594: 
1.79      albertel  595: sub showhashsubset {
1.145     albertel  596:     my ($hash,$keyre) = @_;
                    597:     my $resultkey;
1.346     raeburn   598:     foreach $resultkey (sort(keys(%$hash))) {
1.193     albertel  599: 	if ($resultkey !~ /$keyre/) { next; }
                    600: 	if (ref($$hash{$resultkey})  eq 'ARRAY' ) {
                    601: 	    &Apache::lonxml::debug("$resultkey ---- ".
                    602: 				   &showarray($$hash{$resultkey}));
                    603: 	} elsif (ref($$hash{$resultkey}) eq 'HASH' ) {
                    604: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
                    605: 	    &showhashsubset($$hash{$resultkey},'.');
                    606: 	} else {
                    607: 	    &Apache::lonxml::debug("$resultkey ---- $$hash{$resultkey}");
1.145     albertel  608: 	}
                    609:     }
                    610:     &Apache::lonxml::debug("\n<br />restored values^</br>\n");
                    611:     return '';
1.41      albertel  612: }
                    613: 
                    614: sub setuppermissions {
1.204     albertel  615:     $Apache::lonhomework::browse= &Apache::lonnet::allowed('bre',$env{'request.filename'});
1.337     raeburn   616:     unless ($Apache::lonhomework::browse eq 'F') {
                    617:         $Apache::lonhomework::browse=&Apache::lonnet::allowed('bro',$env{'request.filename'}); 
                    618:     }
1.204     albertel  619:     my $viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
1.145     albertel  620:     if (! $viewgrades && 
1.204     albertel  621: 	exists($env{'request.course.sec'}) && 
                    622: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    623: 	$viewgrades = &Apache::lonnet::allowed('vgr',$env{'request.course.id'}.
                    624:                                                '/'.$env{'request.course.sec'});
1.145     albertel  625:     }
1.244     albertel  626:     $Apache::lonhomework::viewgrades = $viewgrades;
                    627: 
1.185     albertel  628:     if ($Apache::lonhomework::browse eq 'F' && 
1.204     albertel  629: 	$env{'form.devalidatecourseresdata'} eq 'on') {
1.261     albertel  630: 	my (undef,$courseid) = &Apache::lonnet::whichuser();
1.204     albertel  631: 	&Apache::lonnet::devalidatecourseresdata($env{"course.$courseid.num"},
                    632: 					      $env{"course.$courseid.domain"});
1.185     albertel  633:     }
1.244     albertel  634: 
1.205     albertel  635:     my $modifygrades = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
                    636:     if (! $modifygrades && 
                    637: 	exists($env{'request.course.sec'}) && 
                    638: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    639: 	$modifygrades = 
                    640: 	    &Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                    641: 				     '/'.$env{'request.course.sec'});
                    642:     }
                    643:     $Apache::lonhomework::modifygrades = $modifygrades;
1.244     albertel  644: 
                    645:     my $queuegrade = &Apache::lonnet::allowed('mqg',$env{'request.course.id'});
                    646:     if (! $queuegrade && 
                    647: 	exists($env{'request.course.sec'}) && 
                    648: 	$env{'request.course.sec'} !~ /^\s*$/) {
                    649: 	$queuegrade = 
                    650: 	    &Apache::lonnet::allowed('qgr',$env{'request.course.id'}.
                    651: 				     '/'.$env{'request.course.sec'});
                    652:     }
                    653:     $Apache::lonhomework::queuegrade = $queuegrade;
1.205     albertel  654:     return '';
1.41      albertel  655: }
                    656: 
1.253     albertel  657: sub unset_permissions {
                    658:     undef($Apache::lonhomework::queuegrade);
                    659:     undef($Apache::lonhomework::modifygrades);
                    660:     undef($Apache::lonhomework::viewgrades);
                    661:     undef($Apache::lonhomework::browse);
                    662: }
                    663: 
1.41      albertel  664: sub setupheader {
1.120     albertel  665:     my $request=$_[0];
1.197     albertel  666:     &Apache::loncommon::content_type($request,'text/html');
1.120     albertel  667:     if (!$Apache::lonxml::debug && ($ENV{'REQUEST_METHOD'} eq 'GET')) {
                    668: 	&Apache::loncommon::no_cache($request);
                    669:     }
1.196     albertel  670: #    $request->set_last_modified(&Apache::lonnet::metadata($request->uri,
                    671: #							  'lastrevisiondate'));
1.120     albertel  672:     $request->send_http_header;
                    673:     return OK if $request->header_only;
                    674:     return ''
1.41      albertel  675: }
1.35      albertel  676: 
1.47      albertel  677: sub handle_save_or_undo {
1.338     raeburn   678:     my ($request,$problem,$result,$getobjref) = @_;
1.323     www       679: 
1.145     albertel  680:     my $file    = &Apache::lonnet::filelocation("",$request->uri);
                    681:     my $filebak =$file.".bak";
                    682:     my $filetmp =$file.".tmp";
                    683:     my $error=0;
1.323     www       684:     if (($env{'form.problemmode'} eq 'undo') || ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel  685: 	my $error=0;
1.284     albertel  686: 	if (!&File::Copy::copy($file,$filetmp)) { $error=1; }
                    687: 	if ((!$error) && (!&File::Copy::copy($filebak,$file))) { $error=1; }
                    688: 	if ((!$error) && (!&File::Copy::move($filetmp,$filebak))) { $error=1; }
1.145     albertel  689: 	if (!$error) {
1.266     albertel  690: 	    &Apache::lonxml::info("<p><b>".
                    691: 				  &mt("Undid changes, Switched [_1] and [_2]",
                    692: 				      '<span class="LC_filename">'.$filebak.
                    693: 				      '</span>',
                    694: 				      '<span class="LC_filename">'.$file.
                    695: 				      '</span>')."</b></p>");
1.145     albertel  696: 	} else {
1.266     albertel  697: 	    &Apache::lonxml::info("<p><span class=\"LC_error\">".
                    698: 				  &mt("Unable to undo, unable to switch [_1] and [_2]",
                    699: 				      '<span class="LC_filename">'.
                    700: 				      $filebak.'</span>',
                    701: 				      '<span class="LC_filename">'.
                    702: 				      $file.'</span>')."</span></p>");
1.145     albertel  703: 	    $error=1;
                    704: 	}
1.52      albertel  705:     } else {
1.262     banghart  706:         &Apache::lonnet::correct_line_ends($result);
1.323     www       707: 
1.145     albertel  708: 	my $fs=Apache::File->new(">$filebak");
                    709: 	if (defined($fs)) {
                    710: 	    print $fs $$problem;
                    711: 	} else {
1.266     albertel  712: 	    &Apache::lonxml::info("<span class=\"LC_error\">".
                    713: 				  &mt("Unable to make backup [_1]",
                    714: 				      '<span class="LC_filename">'.
                    715: 				      $filebak.'</span>')."</span>");
1.145     albertel  716: 	    $error=2;
                    717: 	}
                    718: 	my $fh=Apache::File->new(">$file");
                    719: 	if (defined($fh)) {
                    720: 	    print $fh $$result;
1.338     raeburn   721:             if (ref($getobjref) eq 'SCALAR') {
                    722:                 if ($file =~ m{([^/]+)\.(html?)$}) {
                    723:                     my $fname = $1;
                    724:                     my $ext = $2;
                    725:                     my $path = $file;
                    726:                     $path =~ s/\Q$fname\E\.\Q$ext\E$//; 
                    727:                     my (%allfiles,%codebase);
                    728:                     &Apache::lonnet::extract_embedded_items($file,\%allfiles,
                    729:                                                            \%codebase,$result);
                    730:                     if (keys(%allfiles) > 0) {
                    731:                         my $url = $request->uri;
                    732:                         my $state = <<STATE;
                    733:     <input type="hidden" name="action" value="upload_embedded" />
                    734:     <input type="hidden" name="url" value="$url" />
                    735: STATE
                    736:                         $$getobjref = "<h3>".&mt("Reference Warning")."</h3>".
                    737:                                       "<p>".&mt("Completed upload of the file. This file contained references to other files.")."</p>".
                    738:                                       "<p>".&mt("Please select the locations from which the referenced files are to be uploaded.")."</p>".
                    739:                                       &Apache::loncommon::ask_for_embedded_content($url,$state,\%allfiles,\%codebase,
                    740:                                       {'error_on_invalid_names'   => 1,
                    741:                                        'ignore_remote_references' => 1,});
                    742:                     }
                    743:                 }
                    744:             }
1.145     albertel  745: 	} else {
1.266     albertel  746: 	    &Apache::lonxml::info('<span class="LC_error">'.
                    747: 				  &mt("Unable to write to [_1]",
                    748: 				      '<span class="LC_filename">'.
                    749: 				      $file.'</span>').
                    750: 				  '</span>');
1.145     albertel  751: 	    $error|=4;
                    752: 	}
1.52      albertel  753:     }
1.145     albertel  754:     return $error;
1.64      albertel  755: }
                    756: 
1.101     albertel  757: sub analyze_header {
                    758:     my ($request) = @_;
1.289     raeburn   759:     my $js = &Apache::structuretags::setmode_javascript();
1.312     bisitz    760: 
                    761:     # Breadcrumbs
1.330     raeburn   762:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn   763:                    'text' => 'Authoring Space'},
1.312     bisitz    764:                   {'href' => '',
                    765:                    'text' => 'Problem Testing'},
                    766:                   {'href' => '',
                    767:                    'text' => 'Analyzing a problem'}];
                    768: 
1.238     albertel  769:     my $result =
1.312     bisitz    770:         &Apache::loncommon::start_page('Analyzing a problem',
                    771:                                        $js,
                    772:                                        {'bread_crumbs' => $brcrum,})
1.311     bisitz    773:        .&Apache::loncommon::head_subbox(
                    774:                 &Apache::loncommon::CSTR_pageheader());
1.238     albertel  775:     $result .= 
1.347     golterma  776: 	    '<form name="lonhomework" method="post" action="'.
1.204     albertel  777: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.289     raeburn   778:             '<input type="hidden" name="problemmode" value="'.
                    779:             $env{'form.problemmode'}.'" />'.
1.179     albertel  780: 	    &Apache::structuretags::remember_problem_state().'
1.278     albertel  781:             <div class="LC_edit_problem_analyze_header">
1.289     raeburn   782:             <input type="button" name="submitmode" value="'.&mt("EditXML").'" '.
                    783:             'onclick="javascript:setmode(this.form,'."'editxml'".')" />
                    784:             <input type="button" name="submitmode" value="'.&mt('Edit').'" '.
                    785:             'onclick="javascript:setmode(this.form,'."'edit'".')" />
1.313     bisitz    786:             <hr />
1.289     raeburn   787:             <input type="button" name="submitmode" value="'.&mt("View").'" '.
                    788:             'onclick="javascript:setmode(this.form,'."'view'".')" />
1.313     bisitz    789:             <hr />
1.347     golterma  790:             </div>'
                    791:             .&Apache::lonxml::message_location().
                    792:             '</form>';
1.171     albertel  793:     &Apache::lonxml::add_messages(\$result);
1.101     albertel  794:     $request->print($result);
                    795:     $request->rflush();
                    796: }
                    797: 
1.109     albertel  798: sub analyze_footer {
                    799:     my ($request) = @_;
1.237     albertel  800:     $request->print(&Apache::loncommon::end_page());
1.109     albertel  801:     $request->rflush();
                    802: }
                    803: 
1.74      albertel  804: sub analyze {
1.101     albertel  805:     my ($request,$file) = @_;
                    806:     &Apache::lonxml::debug("Analyze");
                    807:     my $result;
                    808:     my %overall;
1.219     www       809:     my %seedexample;
1.101     albertel  810:     my %allparts;
1.204     albertel  811:     my $rndseed=$env{'form.rndseed'};
1.101     albertel  812:     &analyze_header($request);
1.114     albertel  813:     my %prog_state=
1.335     www       814: 	&Apache::lonhtmlcommon::Create_PrgWin($request,$env{'form.numtoanalyze'});
1.204     albertel  815:     for(my $i=1;$i<$env{'form.numtoanalyze'}+1;$i++) {
1.335     www       816: 	&Apache::lonhtmlcommon::Increment_PrgWin($request,\%prog_state,'last problem');
1.182     albertel  817: 	if (&Apache::loncommon::connection_aborted($request)) { return; }
1.219     www       818:         my $thisseed=$i+$rndseed;
1.101     albertel  819: 	my $subresult=&Apache::lonnet::ssi($request->uri,
                    820: 					   ('grade_target' => 'analyze'),
1.219     www       821: 					   ('rndseed' => $thisseed));
1.101     albertel  822: 	(my $garbage,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    823: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.114     albertel  824: 	my @parts;
1.336     raeburn   825:         if (ref($analyze{'parts'}) eq 'ARRAY') {
1.114     albertel  826: 	    @parts=@{ $analyze{'parts'} };
                    827: 	}
1.101     albertel  828: 	foreach my $part (@parts) {
                    829: 	    if (!exists($allparts{$part})) {$allparts{$part}=1;};
1.109     albertel  830: 	    if ($analyze{$part.'.type'} eq 'numericalresponse'	||
                    831: 		$analyze{$part.'.type'} eq 'stringresponse'	||
                    832: 		$analyze{$part.'.type'} eq 'formularesponse'   ) {
1.263     albertel  833: 		foreach my $name (keys(%{ $analyze{$part.'.answer'} })) {
                    834: 		    my $i=0;
                    835: 		    foreach my $answer_part (@{ $analyze{$part.'.answer'}{$name} }) {
                    836: 			push( @{ $overall{$part.'.answer'}[$i] },
                    837: 			      $answer_part);
                    838: 			my $concatanswer= join("\0",@{ $answer_part });
                    839: 			if (($concatanswer eq '') || ($concatanswer=~/^\@/)) {
1.266     albertel  840: 			    $answer_part = ['<span class="LC_error">'.&mt('Error').'</span>'];
1.263     albertel  841: 			}
                    842: 			$seedexample{join("\0",$part,$i,@{$answer_part})}=
                    843: 			    $thisseed;
                    844: 			$i++;
                    845: 		    }
1.219     www       846: 		}
1.275     albertel  847: 		if (!keys(%{ $analyze{$part.'.answer'} })) {
                    848: 		    my $answer_part = 
                    849: 			['<span class="LC_error">'.&mt('Error').'</span>'];
                    850: 		    $seedexample{join("\0",$part,0,@{$answer_part})}=
                    851: 			$thisseed;
                    852: 		    push( @{ $overall{$part.'.answer'}[0] },
                    853: 			  $answer_part);
                    854: 		}
1.101     albertel  855: 	    }
                    856: 	}
                    857:     }
1.335     www       858:     &Apache::lonhtmlcommon::Update_PrgWin($request,\%prog_state,&mt('Analyzing Results'));
1.313     bisitz    859:     $request->print('<hr />'
1.308     bisitz    860:                    .'<h3>'
                    861:                    .&mt('List of possible answers')
                    862:                    .'</h3>'
                    863:     );
1.134     albertel  864:     foreach my $part (sort(keys(%allparts))) {
1.336     raeburn   865:         if ((ref($overall{$part.'.answer'}) eq 'ARRAY') &&
                    866:             (@{$overall{$part.'.answer'}} > 0)) {
1.263     albertel  867: 	    for (my $i=0;$i<scalar(@{ $overall{$part.'.answer'} });$i++) {
                    868: 		my $num_cols=scalar(@{ $overall{$part.'.answer'}[$i][0] });
1.308     bisitz    869:                 $request->print(&Apache::loncommon::start_data_table()
                    870:                                .&Apache::loncommon::start_data_table_header_row()
                    871:                                .'<th colspan="'.($num_cols+1).'">'
                    872:                                .&mt('Part').' '.$part
                    873:                 );
1.263     albertel  874: 		if (scalar(@{ $overall{$part.'.answer'} }) > 1) {
1.308     bisitz    875: 		    $request->print(' '.&mt('Answer [_1]',$i+1));
1.263     albertel  876: 		}
1.308     bisitz    877: 		$request->print('</th>'
                    878:                                .&Apache::loncommon::end_data_table_header_row()
                    879:                 );
1.263     albertel  880: 		my %frequency;
                    881: 		foreach my $answer (sort {$a->[0] <=> $b->[0]} (@{ $overall{$part.'.answer'}[$i] })) {
                    882: 		    $frequency{join("\0",@{ $answer })}++;
                    883: 		}
1.308     bisitz    884:                 $request->print(&Apache::loncommon::start_data_table_header_row()
                    885:                                .'<th colspan="'.($num_cols).'">'.&mt('Answer').'</th>'
                    886:                                .'<th>'.&mt('Frequency').'<br />'
                    887:                                .'('.&mt('click for example').')</th>'
                    888:                                .&Apache::loncommon::end_data_table_header_row()
                    889:                 );
1.263     albertel  890: 		foreach my $answer (sort {(split("\0",$a))[0] <=> (split("\0",$b))[0]} (keys(%frequency))) {
1.308     bisitz    891:                     $request->print(&Apache::loncommon::start_data_table_row()
                    892:                                    .'<td>'
                    893:                                    .join('</td><td>',split("\0",$answer))
                    894: 				   .'</td>'
                    895:                                    .'<td>'
                    896:                                    .'<a href="'.$request->uri.'?rndseed='.$seedexample{join("\0",$part,$i,$answer)}.'">'.$frequency{$answer}.'</a>'
                    897: 				   .'</td>'
                    898:                                    .&Apache::loncommon::end_data_table_row()
                    899:                     );
1.263     albertel  900: 		}
1.308     bisitz    901:                 $request->print(&Apache::loncommon::end_data_table());
1.109     albertel  902: 	    }
                    903: 	} else {
1.307     bisitz    904:             $request->print('<p class="LC_warning">'
                    905:                            .&mt('Response [_1] is not analyzable at this time.',$part)
                    906: 			   .'</p>'
                    907:             );
1.101     albertel  908: 	}
                    909:     }
1.130     albertel  910:     if (scalar(keys(%allparts)) == 0 ) {
1.307     bisitz    911:         $request->print('<p class="LC_warning">'
                    912:                        .&mt('Found no analyzable responses in this problem.'
                    913:                            .' Currently only Numerical, Formula and String response styles are supported.')
                    914:                        .'</p>'
                    915:         );
1.130     albertel  916:     }
1.114     albertel  917:     &Apache::lonhtmlcommon::Close_PrgWin($request,\%prog_state);
1.109     albertel  918:     &analyze_footer($request);
1.101     albertel  919:     &Apache::lonhomework::showhash(%overall);
                    920:     return $result;
1.74      albertel  921: }
                    922: 
1.277     albertel  923: {
                    924:     my $show_problem_status;
                    925:     sub reset_show_problem_status {
                    926: 	undef($show_problem_status);
                    927:     }
                    928: 
                    929:     sub set_show_problem_status {
                    930: 	my ($new_status) = @_;
                    931: 	$show_problem_status = lc($new_status);
                    932:     }
                    933: 
                    934:     sub hide_problem_status {
                    935: 	return ($show_problem_status eq 'no'
                    936: 		|| $show_problem_status eq 'no_feedback_ever');
                    937:     }
                    938: 
                    939:     sub show_problem_status {
                    940: 	return ($show_problem_status eq 'yes'
1.285     albertel  941: 		|| $show_problem_status eq 'answer'
1.277     albertel  942: 		|| $show_problem_status eq '');
                    943:     }
                    944:     
                    945:     sub show_some_problem_status {
                    946: 	return ($show_problem_status eq 'no');
                    947:     }
                    948: 
                    949:     sub show_no_problem_status {
                    950: 	return ($show_problem_status eq 'no_feedback_ever');
                    951:     }
1.285     albertel  952:   
                    953:     sub show_answer_problem_status {
                    954: 	return ($show_problem_status eq 'answer');
                    955:     }
1.277     albertel  956: }
                    957: 
1.64      albertel  958: sub editxmlmode {
1.145     albertel  959:     my ($request,$file) = @_;
                    960:     my $result;
                    961:     my $problem=&Apache::lonnet::getfile($file);
                    962:     if ($problem eq -1) {
1.305     bisitz    963: 	&Apache::lonxml::error(
1.328     bisitz    964:             '<p class="LC_error">'
1.305     bisitz    965:            .&mt('Unable to find [_1]',
                    966:                 '<span class="LC_filename">'.$file.'</span>')
1.328     bisitz    967:            .'</p>');
1.305     bisitz    968: 
1.145     albertel  969: 	$problem='';
                    970:     }
1.323     www       971:     if (($env{'form.problemmode'} eq 'saveeditxml') ||
1.347     golterma  972:         ($env{'form.problemmode'} eq 'saveviewxml') ||
1.323     www       973:         ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel  974: 	my $error=&handle_save_or_undo($request,\$problem,
1.204     albertel  975: 				       \$env{'form.editxmltext'});
1.145     albertel  976: 	if (!$error) { $problem=&Apache::lonnet::getfile($file); }
                    977:     }
1.204     albertel  978:     &Apache::lonhomework::showhashsubset(\%env,'^form');
1.323     www       979:     if ($env{'form.problemmode'} eq 'saveviewxml') {
1.204     albertel  980: 	&Apache::lonhomework::showhashsubset(\%env,'^form');
1.289     raeburn   981: 	$env{'form.problemmode'}='view';
1.145     albertel  982: 	&renderpage($request,$file);
                    983:     } else {
                    984: 	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$problem);
                    985: 	if ($cols > 80) { $cols = 80; }
                    986: 	if ($cols < 70) { $cols = 70; }
                    987: 	if ($rows < 20) { $rows = 20; }
1.269     albertel  988: 	my $js =
                    989: 	    &Apache::edit::js_change_detection(). 
1.289     raeburn   990: 	    &Apache::loncommon::resize_textarea_js().
1.296     raeburn   991:             &Apache::structuretags::setmode_javascript().
1.298     foxr      992:             &Apache::lonhtmlcommon::dragmath_js("EditMathPopup");
1.312     bisitz    993: 
                    994:     # Breadcrumbs
1.330     raeburn   995:     my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn   996:                    'text' => 'Authoring Space'},
1.312     bisitz    997:                   {'href' => '',
                    998:                    'text' => 'Problem Editing'}];
                    999: 
1.238     albertel 1000: 	my $start_page = 
1.269     albertel 1001: 	    &Apache::loncommon::start_page(&mt("EditXML [_1]",$file),$js,
                   1002: 					   {'no_auto_mt_title' => 1,
1.318     droeschl 1003: 					    'only_body'        => 0,
1.269     albertel 1004: 					    'add_entries'      => {
                   1005: 						'onresize' => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
                   1006: 						'onload'   => q[resize_textarea('LC_editxmltext','LC_aftertextarea')],
1.323     www      1007:                                                                   },
1.312     bisitz   1008:                                                 'bread_crumbs' => $brcrum,
1.323     www      1009:                                              });
1.311     bisitz   1010: 
                   1011:     $result=$start_page
                   1012:            .&Apache::loncommon::head_subbox(
                   1013:                 &Apache::loncommon::CSTR_pageheader());
                   1014: 	$result.=&renderpage($request,$file,['no_output_web'],1).
1.310     bisitz   1015:             '<form '.&Apache::edit::form_change_detection().' name="lonhomework" method="post" action="'.
1.204     albertel 1016: 	    &HTML::Entities::encode($env{'request.uri'},'<>&"').'">'.
1.179     albertel 1017: 	    &Apache::structuretags::remember_problem_state().'
1.347     golterma 1018:             <div class="LC_edit_problem_header">
                   1019:               <div class="LC_edit_problem_header_title">'.
                   1020:                 &mt('Problem Editing').' '.&Apache::loncommon::help_open_topic('Problem_Editor_XML_Index').
                   1021:               '</div><div class="LC_edit_actionbar" id="actionbar">';
                   1022: 
1.352     droeschl 1023:     $result.='<input type="hidden" name="problemmode" value="saveedit" />'.
1.348     droeschl 1024:                   &Apache::structuretags::problem_edit_buttons('editxml');
1.352     droeschl 1025:     $result.='<div>';
1.347     golterma 1026: 
1.352     droeschl 1027:     $result .= '<ol class="LC_primary_menu" style="display:inline-block;font-size:90%;vertical-align:middle;">';
                   1028: 
                   1029:     unless ($env{'environment.nocodemirror'}) {
                   1030:         # dropdown menus
                   1031:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1032:             &mt("Problem Templates"), template_dropdown_datastructure());
                   1033: 
                   1034:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1035:             &mt("Response Types"), responseblock_dropdown_datastructure());
                   1036: 
                   1037:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1038:             &mt("Conditional Blocks"), conditional_scripting_datastructure());
                   1039: 
                   1040:         $result .= Apache::lonmenu::create_submenu("#", "", 
                   1041:             &mt("Miscellaneous"), misc_datastructure());
                   1042:     }
1.351     droeschl 1043: 
                   1044:     $result .= Apache::lonmenu::create_submenu("#", "", 
                   1045:         &mt("Help") . ' <img src="/adm/help/help.png" alt="' . &mt("Help") .
                   1046:         '" style="vertical-align:text-bottom; height: auto; margin:0; "/>', 
1.352     droeschl 1047:         helpmenu_datastructure(),"");
1.351     droeschl 1048: 
                   1049:     $result.="</ol></div>";
1.323     www      1050:          
1.352     droeschl 1051:     $result .= '</div></div>' . 
                   1052:         &Apache::lonxml::message_location() .
                   1053:         &Apache::loncommon::xmleditor_js() .
                   1054:         '<textarea ' . &Apache::edit::element_change_detection() .
                   1055:         ' rows="'.$rows.'" cols="'.$cols.'" style="width:100%" ' .
                   1056:         ' name="editxmltext" id="LC_editxmltext">' .
                   1057:         &HTML::Entities::encode($problem,'<>&"') .
                   1058:         '</textarea> <div id="LC_aftertextarea"> </div> </form>';
                   1059: 
                   1060:     my $resource = $env{'request.ambiguous'};
                   1061:     unless($env{'environment.nocodemirror'}){
                   1062:         $result .= '<link rel="stylesheet" href="/adm/codemirror/codemirror-combined-xml.css">
                   1063:         <script src="/adm/codemirror/codemirror-compressed-xml.js"></script>
                   1064:         <script>
                   1065:             CodeMirror.defineMode("mixedmode", function(config) {
                   1066:                 return CodeMirror.multiplexingMode(
                   1067:                     CodeMirror.getMode(config, "xml"),
                   1068:                     {
                   1069:                         open: "\<script type=\"loncapa/perl\"\>", close: "\</script\>",
                   1070:                         mode: CodeMirror.getMode(config, "perl"),
                   1071:                         delimStyle: "tag",
                   1072:                     }
                   1073:               );
                   1074:             });
                   1075:             var cm = CodeMirror.fromTextArea(document.getElementById("LC_editxmltext"),
                   1076:             {
                   1077:                 mode: "mixedmode",
                   1078:                 lineWrapping: true,
                   1079:                 lineNumbers: true,
                   1080:                 tabSize: 4,
                   1081:                 indentUnit: 4,
                   1082: 
                   1083:                 autoCloseTags: true,
                   1084:                 autoCloseBrackets: true,
                   1085:                 height: "auto",
                   1086:                 styleActiveLine: true,
                   1087:                 
                   1088:                 extraKeys: {
                   1089:                     "Tab": "indentMore",
                   1090:                     "Shift-Tab": "indentLess",
                   1091:                 }
                   1092:             });
                   1093:             restoreScrollPosition("'.$resource.'");
                   1094:         </script>';
                   1095:     }
                   1096: 
                   1097:     $result .= &Apache::loncommon::end_page();
                   1098:     &Apache::lonxml::add_messages(\$result);
                   1099:     $request->print($result);
1.145     albertel 1100:     }
                   1101:     return '';
1.47      albertel 1102: }
1.189     albertel 1103: 
1.301     jms      1104: #
                   1105: #    Render the page in whatever target desired.
                   1106: #
1.41      albertel 1107: sub renderpage {
1.213     albertel 1108:     my ($request,$file,$targets,$return_string) = @_;
1.52      albertel 1109: 
1.211     albertel 1110:     my @targets = @{$targets || [&get_target()]};
1.204     albertel 1111:     &Apache::lonhomework::showhashsubset(\%env,'form.');
1.145     albertel 1112:     &Apache::lonxml::debug("Running targets ".join(':',@targets));
1.268     albertel 1113: 
1.171     albertel 1114:     my $overall_result;
1.145     albertel 1115:     foreach my $target (@targets) {
1.183     albertel 1116: 	# FIXME need to do something intelligent when a problem goes
                   1117:         # from viewable to not viewable due to map conditions
                   1118: 	#&setuppermissions();
                   1119: 	#if (   $Apache::lonhomework::browse ne '2'
                   1120: 	#    && $Apache::lonhomework::browse ne 'F' ) {
                   1121: 	#    $request->print(" You most likely shouldn't see me.");
                   1122: 	#}
1.145     albertel 1123: 	#my $t0 = [&gettimeofday()];
1.211     albertel 1124: 	my $output=1;
                   1125: 	if ($target eq 'no_output_web') {
                   1126: 	    $target = 'web'; $output=0;
                   1127: 	}
1.145     albertel 1128: 	my $problem=&Apache::lonnet::getfile($file);
1.222     albertel 1129: 	my $result;
1.145     albertel 1130: 	if ($problem eq -1) {
1.260     albertel 1131: 	    $problem='';
1.222     albertel 1132: 	    my $filename=(split('/',$file))[-1];
1.260     albertel 1133: 	    my $error =
1.347     golterma 1134: 		'<p class="LC_error">'
                   1135:                .&mt('Unable to find [_1]',
                   1136: 			   '<span class="LC_filename">'.$filename.'</span>')
                   1137: 		."</p>";
1.260     albertel 1138: 	    $result.=
                   1139: 		&Apache::loncommon::simple_error_page($request,'Not available',
1.340     bisitz   1140: 						      $error,{'no_auto_mt_msg' => 1});
1.260     albertel 1141: 	    return;
1.145     albertel 1142: 	}
1.52      albertel 1143: 
1.145     albertel 1144: 	my %mystyle;
                   1145: 	if ($target eq 'analyze') { %Apache::lonhomework::analyze=(); }
                   1146: 	if ($target eq 'answer') { &showhash(%Apache::lonhomework::history); }
1.204     albertel 1147: 	if ($target eq 'web') {&Apache::lonhomework::showhashsubset(\%env,'^form');}
1.145     albertel 1148: 
                   1149: 	&Apache::lonxml::debug("Should be parsing now");
1.222     albertel 1150: 	$result .= &Apache::lonxml::xmlparse($request, $target, $problem,
                   1151: 					     &setup_vars($target),%mystyle);
1.273     albertel 1152: 	&finished_parsing();
1.214     albertel 1153: 	if (!$output) { $result = ''; }
1.145     albertel 1154: 	#$request->print("Result follows:");
                   1155: 	if ($target eq 'modified') {
                   1156: 	    &handle_save_or_undo($request,\$problem,\$result);
                   1157: 	} else {
                   1158: 	    if ($target eq 'analyze') {
                   1159: 		$result=&Apache::lonnet::hashref2str(\%Apache::lonhomework::analyze);
                   1160: 		undef(%Apache::lonhomework::analyze);
                   1161: 	    }
                   1162: 	    #my $td=&tv_interval($t0);
                   1163: 	    #if ( $Apache::lonxml::debug) {
                   1164: 	    #$result =~ s:</body>::;
                   1165: 	    #$result.="<br />Spent $td seconds processing target $target\n</body>";
                   1166: 	    #}
1.171     albertel 1167: #	    $request->print($result);
                   1168: 	    $overall_result.=$result;
                   1169: #	    $request->rflush();
1.145     albertel 1170: 	}
                   1171: 	#$request->print(":Result ends");
                   1172: 	#my $td=&tv_interval($t0);
1.52      albertel 1173:     }
1.213     albertel 1174:     if (!$return_string) {
                   1175: 	&Apache::lonxml::add_messages(\$overall_result);
                   1176: 	$request->print($overall_result);   
                   1177: 	$request->rflush();   
                   1178:     } else {
                   1179: 	return $overall_result;
                   1180:     }
1.41      albertel 1181: }
                   1182: 
1.273     albertel 1183: sub finished_parsing {
                   1184:     undef($Apache::lonhomework::parsing_a_problem);
                   1185:     undef($Apache::lonhomework::parsing_a_task);
                   1186: }
                   1187: 
1.347     golterma 1188: # function extracted from get_template_html
                   1189: # returns "key" -> list
                   1190: # key: path of template
                   1191: # value 1: title
                   1192: # value 2: category
                   1193: # value 3: name of help topic ???
                   1194: sub get_template_list{
                   1195:     my ($extension) = @_;
                   1196:     
                   1197:     my @files = glob($Apache::lonnet::perlvar{'lonIncludes'}.
                   1198:                      '/templates/*.'.$extension);
                   1199:     @files = map {[$_,&mt(&Apache::lonnet::metadata($_, 'title')),
                   1200:                       (&Apache::lonnet::metadata($_, 'category')?&mt(&Apache::lonnet::metadata($_, 'category')):&mt('Miscellaneous')),
                   1201:                       &mt(&Apache::lonnet::metadata($_, 'help'))]} (@files);
                   1202:     @files = sort {$a->[2].$a->[1] cmp $b->[2].$b->[1]} (@files);
                   1203:     return @files;
                   1204: }
                   1205: 
                   1206: sub get_template_html {
1.282     albertel 1207:     my ($extension) = @_;
1.145     albertel 1208:     my $result;
                   1209:     my @allnames;
                   1210:     &Apache::lonxml::debug("Looking for :$extension:");
1.282     albertel 1211:     my $glob_extension  = $extension;
                   1212:     if ($extension eq 'survey' || $extension eq 'exam') {
                   1213: 	$glob_extension = 'problem';
                   1214:     }
1.347     golterma 1215:     my @files = &get_template_list($extension);
1.287     raeburn  1216:     my ($midpoint,$seconddiv,$numfiles);
1.341     bisitz   1217:     my @noexamplelink = ('blank.problem','blank.library','script.library');
1.287     raeburn  1218:     $numfiles = 0;
                   1219:     foreach my $file (@files) {
                   1220:         next if ($file->[1] !~ /\S/);
                   1221:         $numfiles ++;
                   1222:     }
                   1223:     if ($numfiles > 0) {
                   1224:         $result = '<div class="LC_left_float">';
                   1225:         $midpoint = int($numfiles/2);
                   1226:         if ($numfiles%2) {
                   1227:             $midpoint ++;
                   1228:         }
                   1229:     }
                   1230:     my $count = 0;
1.292     www      1231:     my $currentcategory='';
1.314     bisitz   1232:     my $first = 1;
1.329     raeburn  1233:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.282     albertel 1234:     foreach my $file (@files) {
                   1235: 	next if ($file->[1] !~ /\S/);
1.292     www      1236:         if ($file->[2] ne $currentcategory) {
                   1237:            $currentcategory=$file->[2];
                   1238:            if ((!$seconddiv) && ($count >= $midpoint)) {
1.314     bisitz   1239:                $result .= '</div></div>'."\n".'<div class="LC_left_float">'."\n";
1.292     www      1240:                $seconddiv = 1;
1.314     bisitz   1241:            } elsif (!$first) {
                   1242:                $result.='</div>'."\n";
                   1243:            } else {
                   1244:                $first = 0;
1.292     www      1245:            }
1.314     bisitz   1246:            $result.= '<div class="LC_Box">'."\n"
                   1247:                     .'<h3 class="LC_hcell">'.$currentcategory.'</h3>'."\n";
1.293     www      1248:            $count++;
1.292     www      1249:         }
1.282     albertel 1250: 	$result .=
                   1251: 	    '<label><input type="radio" name="template" value="'.$file->[0].'" />'.
1.292     www      1252: 	    $file->[1].'</label>';
                   1253:         if ($file->[3]) {
                   1254:            $result.=&Apache::loncommon::help_open_topic($file->[3]);
                   1255:         }
1.341     bisitz   1256:         # Provide example link
1.292     www      1257:         my $filename=$file->[0];
1.329     raeburn  1258:         $filename=~s{^\Q$londocroot\E}{};
1.344     raeburn  1259:         if (!(grep($filename =~ /\Q$_\E$/,@noexamplelink))) {
                   1260:             $result .= ' <span class="LC_fontsize_small">'
                   1261:                       .&Apache::loncommon::modal_link(
                   1262:                            $filename.'?inhibitmenu=yes',&mt('Example'),600,420,'sample')
                   1263:                       .'</span>';
                   1264:         }
1.341     bisitz   1265:         $result .= '<br />'."\n";
1.287     raeburn  1266:         $count ++;
                   1267:     }
                   1268:     if ($numfiles > 0) {
1.314     bisitz   1269:         $result .= '</div></div>'."\n".'<div class="LC_clear_float_footer"></div>'."\n";
1.42      albertel 1270:     }
1.145     albertel 1271:     return $result;
1.42      albertel 1272: }
                   1273: 
                   1274: sub newproblem {
1.65      matthew  1275:     my ($request) = @_;
1.282     albertel 1276: 
1.347     golterma 1277: 	if ($env{'form.mode'} eq 'blank'){
                   1278:         my $dest = &Apache::lonnet::filelocation("",$request->uri);
                   1279:         &File::Copy::copy('/home/httpd/html/res/adm/includes/templates/blank.problem',$dest);
                   1280:         &renderpage($request,$dest);
                   1281:         return;
                   1282:     }
1.282     albertel 1283:     if ($env{'form.template'}) {
                   1284: 	my $file = $env{'form.template'};
1.65      matthew  1285: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1286: 	&File::Copy::copy($file,$dest);
1.65      matthew  1287: 	&renderpage($request,$dest);
1.282     albertel 1288: 	return;
                   1289:     }
                   1290: 
                   1291:     my ($extension) = ($request->uri =~ m/\.(\w+)$/);
                   1292:     &Apache::lonxml::debug("Looking for :$extension:");
1.347     golterma 1293:     my $templatelist=&get_template_html($extension);
1.282     albertel 1294:     if ($env{'form.newfile'} && !$templatelist) {
                   1295: 	# no templates found
1.131     albertel 1296: 	my $templatefilename =
1.258     albertel 1297: 	    $request->dir_config('lonIncludes').'/templates/blank.'.$extension;
1.131     albertel 1298: 	&Apache::lonxml::debug("$templatefilename");
                   1299: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.282     albertel 1300: 	&File::Copy::copy($templatefilename,$dest);
1.131     albertel 1301: 	&renderpage($request,$dest);
1.85      albertel 1302:     } else {
1.176     albertel 1303: 	my $url=&HTML::Entities::encode($request->uri,'<>&"');
1.65      matthew  1304: 	my $dest = &Apache::lonnet::filelocation("",$request->uri);
1.128     albertel 1305: 	my $errormsg;
1.85      albertel 1306: 	my $instructions;
1.330     raeburn  1307:         my $brcrum = [{'href' => &Apache::loncommon::authorspace($request->uri),
1.338     raeburn  1308:                        'text' => 'Authoring Space'},
1.312     bisitz   1309:                       {'href' => '',
                   1310:                        'text' => "Create New $extension"}];
1.240     albertel 1311: 	my $start_page = 
1.312     bisitz   1312:             &Apache::loncommon::start_page("Create New $extension",
                   1313:                                            undef,
                   1314:                                            {'bread_crumbs' => $brcrum,});
1.311     bisitz   1315: 	$request->print(
                   1316:         $start_page
                   1317:        .&Apache::loncommon::head_subbox(
                   1318:                 &Apache::loncommon::CSTR_pageheader())
                   1319:        .'<h1>'.&mt("Creating a new $extension resource.")."</h1>
1.128     albertel 1320: $errormsg
1.258     albertel 1321: ".&mt("The requested file [_1] currently does not exist.",
1.329     raeburn  1322:       '<span class="LC_filename">'.$url.'</span>').'
1.314     bisitz   1323: <p class="LC_info">
                   1324: '.&mt("To create a new $extension, select a template from the".
                   1325:       " list below. Then click on the \"Create $extension\" button.").'
                   1326: </p><div><form action="'.$url.'" method="post">');
1.258     albertel 1327: 
1.85      albertel 1328: 	if (defined($templatelist)) {
1.282     albertel 1329: 	    $request->print($templatelist);
1.85      albertel 1330: 	}
1.282     albertel 1331: 	$request->print('<br /><input type="submit" name="newfile" value="'.
                   1332: 			&mt("Create $extension").'" />');
1.314     bisitz   1333: 	$request->print('</form></div>'.&Apache::loncommon::end_page());
1.65      matthew  1334:     }
1.282     albertel 1335:     return;
1.42      albertel 1336: }
                   1337: 
1.268     albertel 1338: sub update_construct_style {
                   1339:     if ($env{'request.state'} eq "construct"
1.289     raeburn  1340: 	&& $env{'form.problemmode'} eq 'view' 
1.268     albertel 1341: 	&&  defined($env{'form.submitted'})
                   1342: 	&& !defined($env{'form.resetdata'})
                   1343: 	&& !defined($env{'form.newrandomization'})) {
                   1344: 	if ((!$env{'form.style_file'} && $env{'construct.style'})
                   1345: 	    ||$env{'form.clear_style_file'}) {
1.303     raeburn  1346: 	    &Apache::lonnet::delenv('construct.style');
1.268     albertel 1347: 	} elsif ($env{'form.style_file'} 
                   1348: 	    && $env{'construct.style'} ne $env{'form.style_file'}) {
1.291     raeburn  1349: 	    &Apache::lonnet::appenv({'construct.style' => 
                   1350: 				        $env{'form.style_file'}});
1.268     albertel 1351: 	}
                   1352:     }
                   1353: }
                   1354: 
1.354     musolffc 1355: #
                   1356: # Sets interval for current user so time left will be zero, either for the entire folder 
                   1357: # containing the current resource, or just the resource, depending on value of first item
                   1358: # in interval array retrieved from EXT("resource.0.interval");
                   1359: #
                   1360: sub zero_timer {
                   1361:     my ($symb) = @_;
                   1362:     my ($hastimeleft,$first_access,$now);
1.356   ! raeburn  1363:     my @interval=&Apache::lonnet::EXT("resource.0.interval",$symb);
1.354     musolffc 1364:     if (@interval > 1) {
                   1365:         if ($interval[1] eq 'course') {
                   1366:             return;
                   1367:         } else {
                   1368:             my $now = time;
                   1369:             my $first_access=&Apache::lonnet::get_first_access($interval[1],$symb);
                   1370:             if ($first_access > 0) {
                   1371:                 if ($first_access+$interval[0] > $now) {
                   1372:                     my $done_time = $now - $first_access;
                   1373:                     my $snum = 1;
                   1374:                     if ($interval[1] eq 'map') {
                   1375:                         $snum = 2;
                   1376:                     }
                   1377:                     my $result = 
                   1378:                         &Apache::lonparmset::storeparm_by_symb_inner($symb,'0_interval',
                   1379:                                                                      $snum,$done_time,
                   1380:                                                                      'date_interval',
                   1381:                                                                      $env{'user.name'},
                   1382:                                                                      $env{'user.domain'});
                   1383:                     return $result;
                   1384:                 }
                   1385:             }
                   1386:         }
                   1387:     }
                   1388:     return;
                   1389: }
1.268     albertel 1390: 
1.41      albertel 1391: sub handler {
1.145     albertel 1392:     #my $t0 = [&gettimeofday()];
                   1393:     my $request=$_[0];
1.354     musolffc 1394: 
1.223     albertel 1395:     $Apache::lonxml::request=$request;
1.204     albertel 1396:     $Apache::lonxml::debug=$env{'user.debug'};
                   1397:     $env{'request.uri'}=$request->uri;
1.180     albertel 1398:     &setuppermissions();
1.193     albertel 1399: 
1.145     albertel 1400:     my $file=&Apache::lonnet::filelocation("",$request->uri);
                   1401: 
                   1402:     #check if we know where we are
1.350     raeburn  1403:     if ($env{'request.course.fn'} && !&Apache::lonnet::symbread('','',1,1)) {
1.145     albertel 1404: 	# if we are browsing we might not be able to know where we are
1.173     albertel 1405: 	if ($Apache::lonhomework::browse ne 'F' && 
1.204     albertel 1406: 	    $env{'request.state'} ne "construct") {
1.145     albertel 1407: 	    #should know where we are, so ask
1.253     albertel 1408: 	    &unset_permissions();
                   1409: 	    $request->internal_redirect('/adm/ambiguous');
                   1410: 	    return OK;
1.145     albertel 1411: 	}
                   1412:     }
1.253     albertel 1413:     if (&setupheader($request)) {
                   1414: 	&unset_permissions();
                   1415: 	return OK;
                   1416:     }
1.354     musolffc 1417: 
1.244     albertel 1418:     &Apache::lonxml::debug("Permissions:$Apache::lonhomework::browse:$Apache::lonhomework::viewgrades:$Apache::lonhomework::modifygrades:$Apache::lonhomework::queuegrade");
1.204     albertel 1419:     &Apache::lonxml::debug("Problem Mode ".$env{'form.problemmode'});
1.261     albertel 1420:     my ($symb) = &Apache::lonnet::whichuser();
1.145     albertel 1421:     &Apache::lonxml::debug('symb is '.$symb);
1.204     albertel 1422:     if ($env{'request.state'} eq "construct") {
1.145     albertel 1423: 	if ( -e $file ) {
                   1424: 	    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1425: 						    ['problemmode']);
1.204     albertel 1426: 	    if (!(defined $env{'form.problemmode'})) {
1.145     albertel 1427: 		#first visit to problem in construction space
1.289     raeburn  1428: 		$env{'form.problemmode'}= 'view';
1.145     albertel 1429: 		&renderpage($request,$file);
1.323     www      1430: 	    } elsif (($env{'form.problemmode'} eq 'editxml') || 
                   1431:                      ($env{'form.problemmode'} eq 'saveeditxml') ||
                   1432:                      ($env{'form.problemmode'} eq 'saveviewxml') ||
                   1433:                      ($env{'form.problemmode'} eq 'undoxml')) {
1.145     albertel 1434: 		&editxmlmode($request,$file);
1.289     raeburn  1435: 	    } elsif ($env{'form.problemmode'} eq 'calcanswers') {
1.145     albertel 1436: 		&analyze($request,$file);
                   1437: 	    } else {
1.268     albertel 1438: 		&update_construct_style();
1.145     albertel 1439: 		&renderpage($request,$file);
                   1440: 	    }
                   1441: 	} else {
1.347     golterma 1442: 		&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   1443: 						    ['mode']);
1.145     albertel 1444: 	    # requested file doesn't exist in contruction space
                   1445: 	    &newproblem($request);
                   1446: 	}
                   1447:     } else {
1.354     musolffc 1448:         # Set the event timer to zero if the "done button" was clicked.  The button is
                   1449:         # part of the doneButton form created in lonmenu.pm
                   1450:         if ($symb && $env{'form.LC_interval_done'} eq 'true') {  
                   1451:             &zero_timer($symb);
                   1452:             undef($env{'form.LC_interval_done'});
                   1453:         }
1.145     albertel 1454: 	# just render the page normally outside of construction space
                   1455: 	&Apache::lonxml::debug("not construct");
1.52      albertel 1456: 	&renderpage($request,$file);
1.41      albertel 1457:     }
1.145     albertel 1458:     #my $td=&tv_interval($t0);
                   1459:     #&Apache::lonxml::debug("Spent $td seconds processing");
                   1460:     # always turn off debug messages
                   1461:     $Apache::lonxml::debug=0;
1.253     albertel 1462:     &unset_permissions();
1.145     albertel 1463:     return OK;
1.52      albertel 1464: 
1.1       albertel 1465: }
                   1466: 
1.352     droeschl 1467: sub template_dropdown_datastructure {
                   1468:     # gathering the all templates and their path, title, category and help topic
                   1469:     my @templates = get_template_list('problem');
                   1470:     # template category => title
                   1471:     my %tmplthash = ();
                   1472:     # template title => path
                   1473:     my %tmpltcontent = ();
                   1474: 	
                   1475:     foreach my $template (@templates){
                   1476:         # put in hash if the template is not empty
                   1477:         unless ($template->[1] eq ''){
                   1478:             push(@{$tmplthash{$template->[2]}}, $template->[1]);
                   1479:             push(@{$tmpltcontent{$template->[1]}},$template->[0]);
                   1480:         }
                   1481:     }
                   1482: 
                   1483: 	my $catList = [];
                   1484:     foreach my $cat (sort keys %tmplthash) {
                   1485: 		my $catItems = [];
                   1486:         foreach my $title (sort @{$tmplthash{$cat}}) {
                   1487:             my $path = $tmpltcontent{$title}->[0];
                   1488:             my $code;
                   1489:             open(FH, "<$path");
                   1490:             while(<FH>){
                   1491:                 $code.= $_ unless $_ =~ /(<problem>)|(<\/problem>)/;
                   1492:             }
                   1493:             close(FH);
                   1494: 
                   1495: 			if ($code ne '') {				
                   1496:                 my $href = 'javascript:insertText(\'' . &convert_for_js(&HTML::Entities::encode($code,'<>&"')) . '\')';
                   1497: 				my $currItem = [$href, $title, undef];
                   1498: 				push @{$catItems}, $currItem;
                   1499: 			}
                   1500:         }
                   1501: 		push @{$catList}, [$catItems, $cat, undef];
                   1502:     }
                   1503: 
                   1504:     return $catList;
                   1505: }
                   1506: 
                   1507: sub responseblock_dropdown_datastructure {
                   1508: 	
                   1509: 	my $mathCat = [
                   1510: 		[
                   1511: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_formularesponse())) . "\')", &mt("Formula Response"), undef],
                   1512: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_functionplotresponse())) . "\')", &mt("Function Plot Response"), undef],
                   1513: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_mathresponse())) . "\')", &mt("Math Response"), undef],
                   1514: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_numericalresponse())) . "\')", &mt("Numerical Response"), undef]
                   1515: 		], 
                   1516: 		&mt("Math"), 
                   1517: 		undef
                   1518: 	];
                   1519: 
                   1520: 	my $miscCat = [		
                   1521: 		[
                   1522:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_imageresponse())) . "\')", &mt("Click on Image"), undef],
                   1523:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_customresponse())) . "\')", &mt("Custom Response"), undef],
                   1524:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_externalresponse())) . "\')", &mt("External Response"), undef],
                   1525:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_matchresponse())) . "\')", &mt("Match Two Lists"), undef],
                   1526:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_radiobuttonresponse())) . "\')", &mt("One out of N statements"), undef],
                   1527:             ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_optionresponse())) . "\')", &mt("Select from Options"), undef], 
                   1528: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_rankresponse())) . "\')", &mt("Rank Values"), undef]
                   1529: 		],
                   1530: 		&mt("Miscellaneous"),
                   1531: 		undef
                   1532: 	];
                   1533: 
                   1534: 	my $chemCat = [
                   1535: 		[
                   1536: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_reactionresponse())) . "\')", &mt("Chemical Reaction"), undef],
                   1537: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicresponse())) . "\')", &mt("Organic Chemical Structure"), undef]
                   1538: 		],
                   1539: 		&mt("Chemistry"),
                   1540: 		undef
                   1541: 	];
                   1542: 
                   1543: 	my $textCat = [
                   1544: 		[
                   1545: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_stringresponse())) . "\')", &mt("String Response"), undef],
                   1546: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_essayresponse())) . "\')", &mt("Essay"), undef]
                   1547: 		],
                   1548: 		&mt("Text"),
                   1549: 		undef
                   1550: 	];
                   1551: 
                   1552:     return [$mathCat, $miscCat, $chemCat, $textCat];
                   1553: }
                   1554: 
                   1555: 
                   1556: sub conditional_scripting_datastructure {
                   1557: # TODO: corresponding routines should be used for the javascript:insertText parts
                   1558: # instead of the placeholder routine default_xml_tag with the tags
                   1559: # e.g. &default_xml_tag("postanswerdate") should be replaced with a routine which
                   1560: # returns the corresponding content for this case
                   1561: 
                   1562: #TODO translated is currently temporarily here, another solution should be found where the
                   1563: # needed string can be retrieved
                   1564: 
                   1565: 	my $translatedTag = '
                   1566: <translated>
                   1567:     <lang which="en"></lang>
                   1568:     <lang which="default"></lang>
                   1569: </translated>';
                   1570:     return [
                   1571: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode($translatedTag)) . "\')", &mt("Translated Block"), undef],
                   1572: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("block"))) . "\')", &mt("Conditional Block"), undef],
                   1573: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("postanswerdate"))) . "\')", &mt("After Answer Date Block"), undef],
                   1574: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("preduedate"))) . "\')", &mt("Before Due Date Block"), undef],
                   1575: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("solved"))) . "\')", &mt("Block For After Solved"), undef],
                   1576: 			["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("notsolved"))) . "\')", &mt("Block For When Not Solved"), undef]
                   1577:         ];
                   1578: }
                   1579: 
                   1580: sub misc_datastructure {
                   1581:     return [
                   1582:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_img())) . "\')", &mt("Image"), undef],
                   1583:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::lonplot::insert_gnuplot())) . "\')", &mt("GNU Plot"), undef],
                   1584:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_organicstructure())) . "\')", &mt("Organic Structure"), undef],
                   1585:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::edit::insert_script())) . "\')", &mt("Script Block"), undef],
                   1586:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("allow"))) . "\')", &mt("File Dependencies"), undef],
                   1587:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("import"))) . "\')", &mt("Import a File"), undef],
1.353     droeschl 1588:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&Apache::londefdef::insert_meta())) . "\')", &mt("Custom Metadata"), undef],
                   1589:         ["javascript:insertText(\'" . &convert_for_js(&HTML::Entities::encode(&default_xml_tag("part"))) . "\')", &mt("Problem Part"), undef]
1.352     droeschl 1590:     ];
                   1591: }
                   1592: 
                   1593: # helper routine for the datastructure building subroutines
                   1594: sub default_xml_tag {
                   1595: 	my ($tag) = @_;
                   1596: 	return "\n<$tag></$tag>";
                   1597: }
                   1598: 
                   1599: 
                   1600: sub helpmenu_datastructure {
                   1601: 
                   1602: 	my $width = 500;
                   1603: 	my $height = 600;
                   1604: 
                   1605: 	my $helpers = [
                   1606: 		['Problem_LON-CAPA_Functions', &mt('Script Functions')],
                   1607: 		['Greek_Symbols', &mt('Greek Symbols')],
                   1608:  		['Other_Symbols', &mt('Other Symbols')],
                   1609: 		['Authoring_Output_Tags', &mt('Output Tags')],
                   1610: 		['Authoring_Multilingual_Problems', 
                   1611: 			&mt('How to create problems in different languages')]
                   1612: 	];
                   1613: 
                   1614: 	my $help_structure = [];
                   1615: 
                   1616: 	foreach my $count (0..(scalar(@{$helpers})-1)) {
                   1617: 		my $filename = $helpers->[$count]->[0];
                   1618: 		my $title = $helpers->[$count]->[1];
                   1619: 		my $href = &HTML::Entities::encode("javascript:openMyModal('/adm/help/$filename.hlp',$width,$height,'yes');");
                   1620: 		push @{$help_structure}, [$href, $title, undef];
                   1621: 	}
                   1622: 
                   1623: 	return $help_structure;
                   1624: }
                   1625: 
                   1626: # we need substitution to not break javascript code
                   1627: sub convert_for_js {
                   1628:     my $return = shift;
                   1629:         $return =~ s|script|ESCAPEDSCRIPT|g;
                   1630:         $return =~ s|\\|\\\\|g;
                   1631:         $return =~ s|\n|\\r\\n|g;
                   1632:         $return =~ s|'|\\'|g;
                   1633: 		$return =~ s|&#39;|\\&#39;|g;
                   1634:     return $return;
                   1635: }
                   1636: 
1.1       albertel 1637: 1;
                   1638: __END__

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