File:  [LON-CAPA] / loncom / homework / essayresponse.pm
Revision 1.100: download - view: text, annotated - select for diffs
Wed Jan 21 16:43:30 2009 UTC (15 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_8_X, version_2_8_2, version_2_8_1, HEAD, GCI_1, BZ5434-fox
- Eliminate unnecessary foreach loop.

    1: # The LearningOnline Network with CAPA
    2: # essay (ungraded) style responses
    3: #
    4: # $Id: essayresponse.pm,v 1.100 2009/01/21 16:43:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::essayresponse;
   30: use strict;
   31: use Apache::lonxml();
   32: use Apache::lonnet;
   33: use Apache::lonlocal;
   34: use LONCAPA qw(:DEFAULT :match);
   35:  
   36: 
   37: BEGIN {
   38:     &Apache::lonxml::register('Apache::essayresponse',('essayresponse'));
   39: }
   40: 
   41: sub start_essayresponse {
   42:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
   43:     my $result;
   44:     my $id = &Apache::response::start_response($parstack,$safeeval);
   45:     if ($target eq 'meta') {
   46: 	$result=&Apache::response::meta_package_write('essayresponse');
   47:     } elsif ($target eq 'web' &&
   48: 	     $Apache::inputtags::status[-1] eq 'CAN_ANSWER') {
   49: 	my $part= $Apache::inputtags::part;
   50: 	my $ncol= &Apache::lonnet::EXT("resource.$part".'_'."$id.maxcollaborators");
   51: 	my $coll= &HTML::Entities::encode($Apache::lonhomework::history{"resource.$part.$id.collaborators"},'<>&"');
   52: 	my $uploadedfiletypes= &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes");
   53:         $uploadedfiletypes=~s/[^\w\,]//g;
   54:         my $maxfilesize=&Apache::lonnet::EXT("resource.$part".'_'."$id.maxfilesize");
   55:         if (!defined($maxfilesize)) {
   56:             $maxfilesize = 10.0; #FIXME This should become a domain configuration 
   57:         }
   58: 	if ( $Apache::lonhomework::type eq 'survey' ) {
   59: 	    $result.= '<input type="hidden" name="HWDRAFT'.$part.'_'.$id.'" value="yes" /> ';
   60: 	}
   61: 	$result.='<br /><table border="1">';
   62: 	if ( $Apache::lonhomework::type ne 'survey' ) {
   63: 	    $result.= '<tr><td>'.
   64: 		'<label>'.
   65: 		'<input type="radio" name="HWDRAFT'.$part.'_'.$id.'" value="yes" checked="checked" /> '.
   66: 		&mt('Submit entries below as answer to receive credit').
   67: 		'</label> <br />'.
   68: 		'<label>'.
   69: 		'<input type="radio" name="HWDRAFT'.$part.'_'.$id.'" value="no" /> '.
   70: 		&mt('Save entries below as a draft answer (not submitting them for credit yet)').
   71: 		'</label>'.
   72: 		'</td></tr>';
   73: 	}
   74: 
   75: 	if ($ncol > 0) {
   76: 	    $result .='<tr><td>'.'<label>'.
   77: 		      &mt('Collaborators:').' <input type="text" size="70" max="80" name="HWCOL'.
   78: 		      $part.'_'.$id.'" value="'.$coll.'" /><br />'.
   79: 		      &mt('(Enter a maximum of [quant,_1,collaborator] using username or username:domain, e.g. smithje or smithje:[_2].)',$ncol,$env{'user.domain'});
   80:             if ($ncol > 1) {
   81:                 $result .= '<br />'.&mt('If entering more than one, use spaces to separate the collaborators.');
   82:             }
   83:             $result .= '</label><br />';
   84: 	    $result .= &check_collaborators($ncol,$coll) if ($coll =~ /\w+/);
   85: 	    $result .='</td></tr>';
   86: 	}
   87:         my $filesfrom = 'both';
   88:         my $stuname = &Apache::lonnet::EXT('user.name');
   89:         my $studom = &Apache::lonnet::EXT('user.domain');
   90:         if (!&Apache::lonnet::usertools_access($stuname,$studom,'portfolio')) {
   91:             $filesfrom = 'uploadonly';
   92:         }
   93: 	$result.=&Apache::inputtags::file_selector($part,$id,$uploadedfiletypes,
   94: 						   $filesfrom,undef,$maxfilesize);
   95:         $result.='</table>';
   96:     } elsif ($target eq 'web' &&
   97: 	     $Apache::inputtags::status[-1] ne 'CAN_ANSWER') {
   98: 	my $part= $Apache::inputtags::part;
   99: 	my @msgs;
  100: 	if ($Apache::lonhomework::history{"resource.$part.$id.collaborators"} =~ /\S/) {
  101: 	    my $coll= &HTML::Entities::encode($Apache::lonhomework::history{"resource.$part.$id.collaborators"},'<>&"');
  102: 	    $result .= '<td>'.&mt('Collaborated with [_1]',$coll).'</td>';
  103: 	}
  104: 
  105: 	my $file_submission = 
  106: 	    &Apache::inputtags::show_past_file_submission($part,$id);
  107: 	if ($file_submission) {
  108: 	    $result .= '<td>'.$file_submission.'</td>';
  109: 	}
  110: 
  111: 	my $port_submission = 
  112: 	    &Apache::inputtags::show_past_portfile_submission($part,$id);
  113: 	if ($port_submission) {
  114: 	    $result .= '<td>'.$port_submission.'</td>';
  115: 	}
  116: 
  117: 	if ($result ne '') {
  118: 	    $result = 
  119: 		'<table class="LC_pastsubmission"><tr>'.$result.
  120: 		'</tr></table>';
  121: 	}
  122:     }
  123:     return $result;
  124: }
  125: 
  126: sub end_essayresponse {
  127:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  128:     my $part          = $Apache::inputtags::part;
  129:     my $id            = $Apache::inputtags::response[-1];
  130:     my $increment     = &Apache::response::repetition();
  131:     my $result;
  132:     if ( $target eq 'grade' ) {
  133: 	my $collaborators = $env{'form.HWCOL'.$part.'_'.$id};	
  134: 	if ($collaborators =~ /[^\s]/) {
  135: 	    my $previous_list= &HTML::Entities::encode($Apache::lonhomework::history{"resource.$part.$id.collaborators"},'<>&"');
  136: 	    $Apache::lonhomework::results{"resource.$part.$id.collaborators"}=$collaborators
  137: 		if ($collaborators ne $previous_list);
  138: 	}
  139: 	if (  &Apache::response::submitted('scantron') ) {
  140: 	    $increment=&Apache::response::scored_response($part,$id);
  141: 	} elsif ( &Apache::response::submitted() ) {
  142: 	    my $response      = $env{'form.HWVAL_'.$id};
  143:             my $filename = $env{'form.HWFILE'.$part.'_'.$id.'.filename'} || 
  144:                            $env{'form.HWFILETOOBIG'.$part.'_'.$id};
  145:             my $portfiles = $env{'form.HWPORT'.$part.'_'.$id};
  146: 	    if (( $response =~ /[^\s]/) || ($filename =~ /[^\s]/) || ($portfiles =~ /[^\s]/)) {
  147:  		my $award='DRAFT';
  148:         	if ($env{'form.HWDRAFT'.$part.'_'.$id} eq 'yes') {
  149: 		    $award='SUBMITTED';
  150: 		}
  151:                 my $uploadedflag=0;
  152:                 my $totalsize=0;
  153: 		&file_submission($part,$id,'filename',\$award,\$uploadedflag,\$totalsize);
  154: 		&file_submission($part,$id,'portfiles',\$award,\$uploadedflag,\$totalsize);
  155: 		$Apache::lonhomework::results{"resource.$part.$id.submission"}=$response;
  156: 		$Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=$award;
  157: 		my %previous=&Apache::response::check_for_previous($response,$part,$id);
  158: 		unless ($uploadedflag) { &Apache::response::handle_previous(\%previous,$award); }
  159: #
  160: # Store with resource author for similarity testing
  161: #
  162:                 if ($award eq 'SUBMITTED') {
  163: 		    my ($symb,$crsid,$domain,$name)=
  164: 			&Apache::lonnet::whichuser();
  165: 		    if ($crsid) {
  166: 			my $akey=join('.',&escape($name),&escape($domain),
  167: 				      &escape($crsid));
  168: 			my $essayurl=
  169: 			    &Apache::lonnet::declutter($ENV{'REQUEST_URI'});
  170: 			my ($adom,$aname,$apath)=
  171: 			    ($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
  172:                         $apath=&escape($apath);
  173: 			$apath=~s/\W/\_/gs;
  174: 			&Apache::lonnet::put('nohist_essay_'.$apath,
  175: 					 { $akey => $response },$adom,$aname);
  176: 		    }
  177:                 }
  178: 	    }
  179: 	} 
  180:     } elsif ($target eq 'edit') {
  181: 	$result.=&Apache::edit::end_table();
  182: 
  183:     } elsif ($target eq 'tex'
  184: 	     && $Apache::lonhomework::type eq 'exam') {
  185: 	$result .= &Apache::inputtags::exam_score_line($target);
  186: 
  187:     } elsif ($target eq 'answer') {
  188: 	$result.=&Apache::response::answer_header($$tagstack[-1]);
  189: 	my $answer = &mt('Essay will be hand graded.');
  190: 	$result.=&Apache::response::answer_part($$tagstack[-1],$answer,
  191: 						{'no_verbatim' => 1});
  192: 	$result.=&Apache::response::answer_footer($$tagstack[-1]);
  193:     }
  194:     if ($target eq 'web') {
  195: 	&Apache::response::setup_prior_tries_hash(\&format_prior_response,
  196: 						  ['portfiles',
  197: 						   'uploadedurl']);
  198:     }
  199: 
  200:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' ||
  201: 	$target eq 'tex' || $target eq 'analyze') {
  202: 	&Apache::lonxml::increment_counter($increment, "$part.$id");
  203: 
  204: 	if ($target eq 'analyze') {
  205:             $Apache::lonhomework::analyze{"$part.$id.type"} = 'essayresponse';
  206:             push (@{ $Apache::lonhomework::analyze{"parts"} },"$part.$id");
  207: 	    &Apache::lonhomework::set_bubble_lines();
  208: 	}
  209:     }
  210:     &Apache::response::end_response;
  211: 
  212:     return $result;
  213: }
  214: 
  215: sub format_prior_response {
  216:     my ($mode,$answer,$other_data) = @_;
  217:     my $output;
  218: 
  219:     my (undef,undef,$udom,$uname) = &Apache::lonnet::whichuser();
  220:     my $port_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio/';
  221: 
  222:     my $file_list;
  223: 
  224:     foreach my $file (split(/\s*,\s*/,
  225: 			    $other_data->[0].','.$other_data->[1])) {
  226: 	next if ($file!~/\S/);
  227: 	if ($file !~ m{^/uploaded/}) { $file=$port_url.$file; }
  228: 	$file=~s|/+|/|g;
  229: 	&Apache::lonnet::allowuploaded('/adm/essayresponse',$file);
  230: 	$file_list.='<li><span class="LC_nobreak"><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.
  231: 	    &Apache::loncommon::icon($file).'" alt="file icon" border="0" /> '.$file.
  232: 	    '</a></span></li>'."\n";
  233:     }
  234:     if ($file_list) {
  235: 	$output.= &mt('Submitted Files').'<ul>'.$file_list.'</ul>';
  236:     }
  237:     if ($answer =~ /\S/) {
  238: 	$output.='<p>'.&mt('Submitted text').
  239: 	    '<blockquote>'.$answer.'</blockquote></p>';
  240:     }
  241: 
  242:     return '<div class="LC_prior_essay">'.$output.'</div>';
  243: }
  244: 
  245: sub file_submission {
  246:     my ($part,$id,$which,$award,$uploadedflag,$totalsize)=@_;
  247:     my $files;
  248:     my $jspart=$part;
  249:     $jspart=~s/\./_/g;
  250:     if ($which eq 'portfiles') { 
  251:         $files= $env{'form.HWPORT'.$jspart.'_'.$id};
  252:     } elsif ($which eq 'filename') {
  253:         if ($env{'form.HWFILETOOBIG'.$jspart.'_'.$id} ne '') {
  254:             $$award = 'EXCESS_FILESIZE';
  255:             return;
  256:         } else {
  257:             $files = $env{'form.HWFILE'.$jspart.'_'.$id.'.filename'};
  258:         }
  259:     }
  260:     if ($files =~ /[^\s]/) {
  261: 	$files =~s/,$//;
  262:         my (@submitted_files,@acceptable_files,@accepted_files);
  263:         if ($which eq 'portfiles') {
  264:             @submitted_files = split(/\s*,\s*/,$files);
  265:         } else {
  266:             @submitted_files = ($files);
  267:         }
  268:         my $uploadedfiletypes= 
  269:             &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes");
  270:         if ($uploadedfiletypes ne '') {
  271:             $uploadedfiletypes=~s/[^\w\,]//g;
  272:             $uploadedfiletypes=','.$uploadedfiletypes.',';
  273:             foreach my $file (@submitted_files) {
  274:                 my ($extension)=($file=~/\.(\w+)$/);
  275:                 if ($uploadedfiletypes=~/\,\s*\Q$extension\E\s*\,/i) {
  276:                     push(@acceptable_files,$file);
  277:                 } else {
  278:                     $$award='INVALID_FILETYPE';
  279:                     if ($which eq 'filename') {
  280:                         &delete_form_items($jspart,$id);
  281:                     }
  282:                 }
  283:             }
  284:         } else {
  285:             @acceptable_files = @submitted_files;
  286:         }
  287:         my $maxfilesize=&Apache::lonnet::EXT("resource.$part".'_'."$id.maxfilesize");
  288:         if (!$maxfilesize) {
  289:             $maxfilesize = 10.0; #FIXME This should become a domain configuration
  290:         }
  291:         my %dirlist;
  292:         foreach my $file (@acceptable_files) {
  293:             if ($which eq 'filename') {
  294:                 if (ref($totalsize)) {
  295:                     $$totalsize += $env{'form.HWFILESIZE'.$jspart.'_'.$id};
  296:                 }
  297:             } else {
  298:                 my ($symb,$crsid,$udom,$uname) = &Apache::lonnet::whichuser();
  299:                 my ($path,$filename) = ($file =~ m{^(.*/)([^/]+)$});
  300:                 my $fullpath = '/userfiles/portfolio'.$path;
  301:                 if (!exists($dirlist{$fullpath})) {
  302:                     my @list = &Apache::lonnet::dirlist($fullpath,$udom,$uname,1);
  303:                     $dirlist{$fullpath} = \@list;
  304:                 }
  305:                 if (ref($dirlist{$fullpath}) eq 'ARRAY') {
  306:                     foreach my $dir_line (@{$dirlist{$fullpath}}) {
  307:                         my ($fname,$dom,undef,$testdir,undef,undef,undef,undef,
  308:                             $size,undef,$mtime,undef,undef,undef,$obs,undef) = 
  309:                         split(/\&/,$dir_line,16);
  310:                         if ($filename eq $fname) {
  311:                             my $mbsize = $size/(1024.0*1024.0);
  312:                             if (ref($totalsize)) {
  313:                                 $$totalsize += $mbsize;
  314:                             }
  315:                             last;
  316:                         }
  317:                     }
  318:                 }
  319:             }
  320:             if (ref($totalsize)) {
  321:                 if ($$totalsize > $maxfilesize) {
  322:                     $$award='EXCESS_FILESIZE';
  323:                     if ($which eq 'filename') {
  324:                         &delete_form_items($jspart,$id);
  325:                     }
  326:                     last;
  327:                 } else {
  328:                     push(@accepted_files,$file);
  329:                 }
  330:             } else {
  331:                 push(@accepted_files,$file);
  332:             }
  333:         }
  334:         $Apache::lonhomework::results{"resource.$part.$id.$which"}=join(',',@accepted_files);
  335:         if (($$award eq 'INVALID_FILETYPE') || ($award eq 'EXCESS_FILESIZE')) {
  336:             return;
  337:         }
  338: 	if (ref($uploadedflag)) {
  339: 	    $$uploadedflag=1;
  340: 	}
  341:         my ($symb,$crsid,$domain,$name)=&Apache::lonnet::whichuser();
  342: 	if ($which eq 'portfiles') {
  343: 	    &Apache::lonnet::unmark_as_readonly($domain,$name,[$symb,$crsid]);
  344: 	    &Apache::lonnet::mark_as_readonly($domain,$name,\@submitted_files,[$symb,$crsid]);
  345: 	    &Apache::lonnet::clear_selected_files($name);
  346: 	}
  347: 	if ($which eq 'filename') {
  348: 	    $Apache::lonhomework::results{"resource.$part.$id.uploadedfile"}=
  349: 		$files;
  350:             my $cleanpart = $part;
  351:             $cleanpart =~ s/\W/_/g;
  352:             my $cleanid = $id;
  353:             $cleanid =~ s/\W/_/g;
  354:             my ($map,$resid,$res)=&Apache::lonnet::decode_symb($symb);
  355:             my $container;
  356:             if ($map =~ /^uploaded/) {
  357:                 (my $prefix,$container) = ($map =~ m{^uploaded/[^/]+/[^/]+/(default|supplemental)_?([^.]*)\.(?:sequence|page)$});
  358:                 if (length($container) > 10) {
  359:                     $container = substr($container,-10,10);
  360:                 }
  361:                 if ($container ne '') {
  362:                     $container = $prefix.'_'.$container;
  363:                 } else {
  364:                     $container = $prefix;
  365:                 } 
  366:             } else {
  367:                 ($container) = ($map =~ m{(.+)\.(?:sequence|page)$});
  368:                 $container =~ s/\W/_/g;
  369:                 if (length($container) > 255) {
  370:                     $container = substr($container,0,254);
  371:                 }
  372:             }
  373:             my $subdir = 'essayresponse';
  374:             my %crsdesc = &Apache::lonnet::coursedescription($crsid);
  375:             foreach my $item ($crsdesc{'domain'},$crsdesc{'num'},$container,$resid,$cleanpart,$cleanid) {
  376:                 if ($item ne '') {
  377:                     $subdir .= '/'.$item;
  378:                 }
  379:             }
  380: 	    $Apache::lonhomework::results{"resource.$part.$id.uploadedurl"}=
  381: 		&Apache::lonnet::userfileupload('HWFILE'.$jspart.'_'.$id,undef,
  382: 						$subdir);
  383:             delete($env{'form.HWFILE'.$jspart.'_'.$id});
  384: 	}
  385:     } elsif ($which eq 'portfiles' &&
  386: 	     $Apache::lonhomework::history{"resource.$part.$id.$which"}) {
  387: 	my ($symb,$crsid,$domain,$name)=&Apache::lonnet::whichuser();
  388: 	&Apache::lonnet::unmark_as_readonly($domain,$name,[$symb,$crsid]);
  389: 	$Apache::lonhomework::results{"resource.$part.$id.$which"}="";
  390:     }
  391: }
  392: 
  393: sub delete_form_items {
  394:     my ($jspart,$id) = @_;
  395:     delete($env{'form.HWFILE'.$jspart.'_'.$id.'.filename'});
  396:     delete($env{'form.HWFILE'.$jspart.'_'.$id.'.mimetype'});
  397:     delete($env{'form.HWFILE'.$jspart.'_'.$id});
  398: }
  399: 
  400: 
  401: sub check_collaborators {
  402:     my ($ncol,$coll) = @_;
  403:     my %classlist=&Apache::lonnet::dump('classlist',
  404: 					$env{'course.'.$env{'request.course.id'}.'.domain'},
  405: 					$env{'course.'.$env{'request.course.id'}.'.num'});
  406:     my (@badcollaborators,$result);
  407:   
  408:     my (@collaborators) = split(/,?\s+/,$coll);
  409:     foreach my $entry (@collaborators) {
  410:         my $collaborator;
  411: 	if ($entry =~ /:/) {
  412: 	    $collaborator = $entry;
  413: 	} else {
  414: 	    $collaborator = $entry.':'.$env{'user.domain'};
  415: 	}
  416:         if ($collaborator !~ /^$match_username:$match_domain$/) {
  417:             if (!grep(/^\Q$entry\E$/,@badcollaborators)) {
  418: 	        push(@badcollaborators,$entry);
  419:             }
  420:         } elsif (!grep(/^\Q$collaborator\E$/i,keys(%classlist))) {
  421:             if (!grep(/^\Q$entry\E$/,@badcollaborators)) {
  422:                 push(@badcollaborators,$entry);
  423:             }
  424:         }
  425:     }
  426:     
  427:     my $numbad = scalar(@badcollaborators);
  428:     if ($numbad) {
  429: 	$result = '<table border="0"><tr bgcolor="#ffbbbb"><td>';
  430:         if ($numbad == 1) {
  431:             $result .= &mt('The following user is invalid:');
  432:         } else {
  433:             $result .= &mt('The following [_1] users are invalid:',$numbad);
  434:         }
  435: 	$result .= ' '.join(', ',@badcollaborators).'. '.&mt('Please correct.').
  436:                    '</td></tr></table>';
  437:     }
  438:     my $toomany = scalar(@collaborators) - $ncol;
  439:     if ($toomany > 0) {
  440: 	$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>'.
  441: 	           &mt('You have too many collaborators.').' '.
  442:                    &mt('Please remove [quant,_1,collaborator].',$toomany).
  443: 	           '</td></tr></table>';
  444:     }
  445:     return $result;
  446: }
  447: 
  448: 1;
  449: __END__
  450: 
  451: 
  452: =pod
  453: 
  454: =head1 NAME
  455: 
  456: Apache::easyresponse
  457: 
  458: =head1 SYNOPSIS
  459: 
  460: Handler to evaluate essay (ungraded) style responses.
  461: 
  462: This is part of the LearningOnline Network with CAPA project
  463: described at http://www.lon-capa.org.
  464: 
  465: =head1 SUBROUTINES
  466: 
  467: =over 
  468: 
  469: =item start_essayresponse()
  470: 
  471: =item end_essayresponse()
  472: 
  473: =item format_prior_response()
  474: 
  475: =item file_submission()
  476: 
  477: =item delete_form_items()
  478: 
  479: =item check_collaborators()
  480: 
  481: =back
  482: 
  483: =cut

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