File:  [LON-CAPA] / loncom / interface / lonpdfupload.pm
Revision 1.21: download - view: text, annotated - select for diffs
Wed Nov 2 15:14:21 2011 UTC (12 years, 6 months ago) by bisitz
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
Ignore case in check for valid PDF file extension

    1: # The LearningOnline Network with CAPA
    2: # PDF Form Upload Handler
    3: #
    4: # $Id: lonpdfupload.pm,v 1.21 2011/11/02 15:14:21 bisitz 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: package Apache::lonpdfupload;
   29: 
   30: use lib '/home/httpd/lib/perl';
   31: use Apache::Constants qw(:common :http);
   32: use Apache::lonnet;
   33: use Apache::lonhtmlcommon();
   34: use Apache::loncommon();
   35: use Apache::lonnavmaps();
   36: use Apache::lonlocal;
   37: use File::MMagic;
   38: use CAM::PDF;
   39: use LONCAPA qw(:DEFAULT :match);
   40: 
   41: use strict;
   42: 
   43: sub handler() {
   44:     my $r = shift;
   45:     &Apache::loncommon::content_type($r,'text/html');
   46:     $r->send_http_header;
   47:     return OK if $r->header_only;
   48: 
   49:     #  Needs to be in a course
   50:     if (!$env{'request.course.fn'}) {
   51:         # Not in a course
   52:         $env{'user.error.msg'}="/adm/pdfupload:bre:0:0:Cannot upload PDF forms unless in a course";
   53:         return HTTP_NOT_ACCEPTABLE;
   54:     }
   55: 
   56:     # Breadcrumbs
   57:     my $brcrum = [{'href' => '/adm/pdfupload',
   58:                    'text' => 'Upload PDF Form'}];
   59:     if ($env{'form.Uploaded'} && $env{'form.file'}) {
   60:         push(@{$brcrum},{'href'  => '',
   61:                          'text'  => 'PDF upload result'});
   62:     }
   63: 
   64:     $r->print(&Apache::loncommon::start_page('Upload PDF Form',
   65:                                              undef,
   66:                                              {'bread_crumbs' => $brcrum,})
   67:     );
   68: 
   69:     if ($env{'request.course.id'}) {
   70:         my $permission = $env{'course.'.$env{'request.course.id'}.'.canuse_pdfforms'};
   71:         if ($permission eq '') {
   72:             my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
   73:             $permission = $domdefs{'canuse_pdfforms'};
   74:         }
   75:         unless ($permission) {
   76:             $r->print('<p class="LC_warning">'.
   77:                       &mt('Upload of PDF forms is not permitted for this course.').
   78:                       '</p>'.
   79:                       &Apache::loncommon::end_page());
   80:             return OK;
   81:         }
   82:     } else {
   83:         $r->print('<p class="LC_warning">'.
   84:                   &mt('Could not determine identity of this course.').' '.
   85:                   &mt('You may need to [_1]re-select[_2] the course.','<a href="/adm/roles">','</a>').
   86:                   '</p>'.
   87:                   &Apache::loncommon::end_page());
   88:         return OK;
   89:     }
   90: 
   91:     # if a file was upload
   92:     if($env{'form.Uploaded'} && $env{'form.file'}) {
   93:         my $mm = new File::MMagic;
   94:         my $mime_type = $mm->checktype_contents($env{'form.file'});
   95:         if ($mime_type eq 'application/pdf') {
   96:             $r->print(&processPDF);
   97:         } else {
   98:             $r->print('<p class="LC_error">'
   99:                      .&mt("The uploaded file does not appear to be a PDF file.")
  100:                      .'</p>');
  101:         }
  102:     } else { 
  103:         # print upload form
  104:         $r->print(&get_javascripts);
  105:         $r->print(&get_uploadform);
  106:     }
  107: 
  108:     #link to course-content
  109:     $r->print('<hr />'
  110:              .'<p>'."\n"
  111:              .'<a href="/adm/navmaps">'."\n"
  112:              .&mt('Course Contents')."\n"
  113:              .'</a>'."\n"
  114:              .'</p>'."\n"
  115:     );
  116: 
  117:     #&dumpenv($r); #debug -> prints the environment
  118:     $r->print(&Apache::loncommon::end_page());
  119:     return OK;
  120: }
  121: 
  122: sub get_javascripts() {
  123:     
  124:     my $message = &mt('Please choose a PDF-File.');
  125: 
  126:     # simple test if the upload ends with ".pdf"
  127:     # it's only for giving a message to the user
  128:     my $result .= <<END
  129:   <script type="text/javascript">
  130: // <![CDATA[
  131:     function checkFilename(form) {
  132:         var fileExt = form.file.value;
  133:         fileExt = fileExt.match(/[.]pdf\$/gi);
  134:         if(fileExt) {
  135:             return true;
  136:         }
  137:         alert("$message");
  138:         return false;
  139:     }
  140: // ]]>
  141:   </script>
  142: END
  143: ;
  144:     return $result; 
  145: }
  146: 
  147: 
  148: sub get_uploadform() {
  149:     
  150:     my %lt = &Apache::lonlocal::texthash(
  151:                  'title'  => 'Upload a PDF Form with filled Form Fields', 
  152:                  'chFile' => 'File',
  153:                  'submit' => 'Upload',
  154:              );
  155: 
  156:     my $result = 
  157:         '<br />'
  158:        .'<form method="post" enctype="multipart/form-data" onsubmit="return checkFilename(this);" action="">'
  159:        .&Apache::lonhtmlcommon::start_pick_box()
  160:        .&Apache::lonhtmlcommon::row_headline()
  161:        .'<h2>'.$lt{'title'}.'</h2>'
  162:        .&Apache::lonhtmlcommon::row_closure()
  163:        .&Apache::lonhtmlcommon::row_title($lt{'chFile'})
  164:        .'<input type="file" name="file" id="filename" />'
  165:        .&Apache::lonhtmlcommon::row_closure(1)
  166:        .&Apache::lonhtmlcommon::end_pick_box()
  167:        .'<p>'
  168:        .'<input type="submit" name="Uploaded" value="'.$lt{'submit'}.'" />'
  169:        .'</p>'
  170:        .'</form>'
  171:        .'<br />';
  172: 
  173:   return $result;
  174: }
  175: 
  176: sub processPDF {
  177:     my $result = ();  # message for Browser
  178:     my @pdfdata = (); # answers from PDF-Forms
  179:     
  180:     @pdfdata = &get_pdf_data(); # get answers from PDF-Form
  181:     
  182:     if (scalar @pdfdata) {    
  183:         &grade_pdf(@pdfdata);
  184:     } else {
  185:         $result .= '<p class="LC_error">'
  186:                   .&mt("Can't find any valid PDF formfields.")
  187:                   .'</p>';
  188:     }
  189: }
  190: 
  191: sub get_pdf_data() {
  192:     my @data = ();
  193:     my $pdf = CAM::PDF->new($env{'form.file'});
  194: 
  195:     if($pdf) {
  196:         my @formFields = $pdf->getFormFieldList(); #get names of formfields
  197: 
  198:         foreach my $field (@formFields) {
  199:             my $dict = $pdf->getFormFieldDict($pdf->getFormField($field)); # get formfield dictonary
  200: 
  201:             # this is necessary because CAM::PDF has a problem with formfieldnames which include a
  202:             # dot in fieldnames. So a fieldname like "i.am.aFormfield" will offer three fieldnames
  203:             # "i", "i.am" and "i.am.aFormfield". The fragmentary names keep no values and will be ignored.
  204:             if($dict->{'V'}) {
  205:                 push(@data, $field."?". $dict->{'V'}{'value'}); #binding fieldname with value
  206:             }
  207:         }
  208:     }
  209:     return @data;
  210: }
  211: 
  212: sub grade_pdf {
  213:     my @pdfdata = @_;
  214:     my ($result,$meta,%grades,%problems,%foreigncourse,$debug);
  215: 
  216:     my $navmap = Apache::lonnavmaps::navmap->new();
  217:     if (!defined($navmap)) {
  218:         $result = '<h3>'.&mt('Verification of PDF form items failed').'</h3>'.
  219:                   '<div class="LC_error">'.
  220:                   &mt('Unable to retrieve information about course contents').' '.
  221:                   &mt('You may need to [_1]re-select[_2] the course.','<a href="/adm/roles">','</a>').
  222:                   '</div>';
  223:         return $result;
  224:     }
  225:     my %restitles;
  226:     foreach my $res ($navmap->retrieveResources()) {
  227:         my $symb = $res->symb; 
  228:         $restitles{$symb} = $res->compTitle();
  229:     }
  230:    
  231:     $debug  .= "Found: ". scalar @pdfdata." Entries \n";
  232: 
  233:     foreach my $entry (sort(@pdfdata)) {
  234:         if ($entry =~ /^meta.*/) {
  235:             $debug .= 'found: metadata -> '.$entry . "<br />";
  236:             my ($label, $value) = ($entry =~ /^([^?]*)\?(.*)/);
  237:             my ($domain, $user) = split('&', $value);
  238:             $user =~ s/(.*)\n/$1/; #TODO is that equals to chomp?
  239:             if($user ne $env{'user.name'} or  $domain ne $env{'user.domain'}) {
  240:                 return '<p class="LC_error">'
  241:                       .&mt('Wrong username ([_1]) found in PDF file. Expected username: [_2]'
  242:                           ,$user.':'.$domain
  243:                           ,$env{'user.domain'}.':'.$env{'user.name'})
  244:                       .'</p>';
  245:             }
  246: 
  247:         } elsif ($entry =~ /^upload.*/)  {
  248:             $debug .= 'found: a problem -> '.$entry;
  249:             my ($label, $value) = ($entry =~ /^([^?]*)\?(.*)/);
  250:             my ($symb, $part, $type, $HWVAL) = split('&', $label);
  251:             my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
  252:             if ($map =~ m{^uploaded/($match_domain)/($match_courseid)/default(_?\d*)\.(page|sequence)}) {
  253:                 my $mapcid = $1.'_'.$2;
  254:                 if ($mapcid ne $env{'request.course.id'}) {
  255:                     push(@{$foreigncourse{$mapcid}},$symb);
  256:                 }
  257:             }
  258:             next unless (exists($restitles{$symb}));
  259:             $value =~ s/(.*)\n/$1/; 
  260: 
  261:             #filter incorrect radiobuttons (Bug in CABAReT Stage)
  262:             if ($type eq 'radiobuttonresponse' && $value eq 'Off' ) {
  263:                 next;
  264:             }
  265:  
  266:             my $submit = $part;
  267:             $submit =~ s/part_(.*)/submit_$1/;
  268:             if ($problems{$symb.$part}) {
  269:                  $problems{$symb.$part}{$HWVAL} = $value;
  270:             } else {
  271:                  $problems{$symb.$part} =  { 'resource' => $resource,
  272:                                         'symb' => $symb,
  273:                                         'submitted' => $part,
  274:                                         $submit => 'Answer',
  275:                                         $HWVAL => $value};
  276:             }
  277:         } else {
  278:             $debug .= 'found: -> '.$entry;
  279:             next;
  280:         }
  281:     }
  282:     #$result .= $debug;
  283: 
  284:     $result .= '<h3>'.&mt('Result of PDF Form upload').'</h3>';
  285: 
  286:     if (keys(%problems) > 0) {
  287:         $result .= &Apache::loncommon::start_data_table()
  288:                   .&Apache::loncommon::start_data_table_header_row()
  289:                   .'<th>'.&mt('Problem Name').'</th>'
  290:                   .'<th>'.&mt('Grading').'</th>'
  291:                   .&Apache::loncommon::start_data_table_header_row()
  292:                   .&Apache::loncommon::end_data_table_header_row();
  293: 
  294:         foreach my $key (sort(keys(%problems))) {
  295:             my %problem = %{$problems{$key}};
  296:             my ($problemname, $grade) = &grade_problem(%problem);
  297: 
  298:             $result .= &Apache::loncommon::start_data_table_row();
  299:             $result .= '<td><a href="/res/'.$problem{'resource'}.
  300:                        '?symb='.
  301:                        &HTML::Entities::encode($problem{'symb'},'"&<>').
  302:                        '">'.$problemname.'</a></td><td class="';
  303:             if ($grade eq "EXACT_ANS" || $grade eq "APPROX_ANS") {
  304:                 $result .= 'LC_answer_correct';
  305:             } else { 
  306:                 $result .= 'LC_answer_charged_try';
  307:             }
  308:             $result .= '">';
  309:             $grade = &parse_grade_answer($grade);
  310:             $result .= $grade.'</span></td>';
  311:             $result .= &Apache::loncommon::end_data_table_row();
  312:         }
  313:         $result .= &Apache::loncommon::end_data_table();
  314:     } else {
  315:         $result .= '<p class="LC_warning">'.
  316:                    &mt('As no gradable form items were found, no submissions have been recorded.').
  317:                    '</p>';
  318:     }
  319:     if (keys(%foreigncourse)) {
  320:         my ($numother,$othercrsmsg);
  321:         foreach my $cid (sort(keys(%foreigncourse))) {
  322:             my %coursehash = &Apache::lonnet::coursedescription($cid,
  323:                                                           {'one_time' => 1});
  324:             if (ref($foreigncourse{$cid}) eq 'ARRAY') {
  325:                 if ($numother) {
  326:                     $othercrsmsg .= '</li><li>';
  327:                 }
  328:                 $othercrsmsg .= '<b>'.$coursehash{'description'}.'</b><ul>'."\n";
  329:                 foreach my $symb (@{$foreigncourse{$cid}}) {
  330:                     my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
  331:                     $othercrsmsg .= '<li>'.$resource.'</li>';
  332:                 }
  333:                 $othercrsmsg .= '</ul>';
  334:                 $numother ++;
  335:             }
  336:         }
  337:         if ($numother) {
  338:             $result .= '<div class="LC_warning">';
  339:             if ($numother > 1) {
  340:                 $result .= &mt('Your uploaded PDF form contained the following resource(s) from [_1] different courses:','<b>'.$numother.'</b>')."\n".'<ul><li>'.
  341:                            $othercrsmsg.'</li></ul>';
  342:             } else {
  343:                 $result .= &mt('Your uploaded PDF form contained the following resource(s) from a different course:').' '.$othercrsmsg.
  344:                            &mt('Did you download the PDF form from another course and upload it to the wrong course?'); 
  345:             }
  346:             $result .= '</div>';
  347:         }
  348:     }
  349: 
  350:     return $result;
  351: }
  352: 
  353: sub grade_problem {
  354:     my %problem = @_;
  355:     my ($title, $part) = ();
  356: 
  357:     &Apache::loncommon::ssi_with_retries('/res/'.$problem{'resource'}, 5, %problem);
  358: 
  359:     $title = &Apache::lonnet::gettitle($problem{'symb'});    
  360:     $part = $problem{submitted};
  361:     $part =~ s/part_(.*)/$1/;
  362:     unless($part eq '0') {
  363:         #add information about part number
  364:         $title .= " - Part $part";
  365:     }
  366:  
  367:     my %problemhash = &Apache::lonnet::restore($problem{'symb'});
  368:     my $grade = $problemhash{"resource.$part.award"};
  369: 
  370:     return ($title, $grade);    
  371: }
  372: 
  373: sub parse_grade_answer {
  374:     my ($shortcut) = @_;
  375:      my %answerhash = ('EXACT_ANS' => &mt('You are correct.'),
  376:                        'APPROX_ANS' => &mt('You are correct.'),
  377:                        'INCORRECT' => &mt('You are incorrect'),
  378:      );
  379: 
  380:     foreach my $key (keys %answerhash) {
  381:         if($shortcut eq $key) {
  382:             return $answerhash{$shortcut};
  383:         }  
  384:     }
  385:     return &mt('See course contents for further information.');
  386: 
  387: }
  388: 
  389: 
  390: sub dumpenv  {
  391:     my $r = shift;
  392: 
  393:     $r->print ("<br />-------------------<br />");
  394:     foreach my $key (sort (keys %env)) {
  395:         $r->print ("<br />$key -> $env{$key}");
  396:     }
  397:     $r->print ("<br />-------------------<br />");
  398:     $r->print ("<br />-------------------<br />");
  399:     foreach my $key (sort (keys %ENV)) {
  400:         $r->print ("<br />$key -> $ENV{$key}");
  401:     }
  402:     $r->print ("<br />-------------------<br />");
  403:     
  404: }	
  405: 
  406: 1;
  407: __END__
  408: 

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