File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.28: download - view: text, annotated - select for diffs
Sun Sep 1 06:23:19 2002 UTC (21 years, 9 months ago) by stredwic
Branches: MAIN
CVS tags: HEAD
First, fixed a typo in lonstudentassessment.  Also, fixed the updating of
the statistics information if the resource tree changes.  Note, in
student assessment it will show up as a blank space unless an attempt
was made for that problem.

    1: # The LearningOnline Network with CAPA
    2: # (Publication Handler
    3: #
    4: # $Id: loncoursedata.pm,v 1.28 2002/09/01 06:23:19 stredwic 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: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: loncoursedata
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: Set of functions that download and process student and course information.
   39: 
   40: =head1 PACKAGES USED
   41: 
   42:  Apache::Constants qw(:common :http)
   43:  Apache::lonnet()
   44:  Apache::lonhtmlcommon
   45:  HTML::TokeParser
   46:  GDBM_File
   47: 
   48: =cut
   49: 
   50: package Apache::loncoursedata;
   51: 
   52: use strict;
   53: use Apache::Constants qw(:common :http);
   54: use Apache::lonnet();
   55: use Apache::lonhtmlcommon;
   56: use HTML::TokeParser;
   57: use GDBM_File;
   58: 
   59: =pod
   60: 
   61: =head1 DOWNLOAD INFORMATION
   62: 
   63: This section contains all the functions that get data from other servers 
   64: and/or itself.
   65: 
   66: =cut
   67: 
   68: # ----- DOWNLOAD INFORMATION -------------------------------------------
   69: 
   70: =pod
   71: 
   72: =item &DownloadClasslist()
   73: 
   74: Collects lastname, generation, middlename, firstname, PID, and section for each
   75: student from their environment database.  The section data is also download, though
   76: it is in a rough format, and is processed later.  The list of students is built from
   77: collecting a classlist for the course that is to be displayed.  Once the classlist
   78: has been downloaded, its date stamp is recorded.  Unless the datestamp for the
   79: class database is reset or is modified, this data will not be downloaded again.  
   80: Also, there was talk about putting the fullname and section
   81: and perhaps other pieces of data into the classlist file.  This would
   82: reduce the number of different file accesses and reduce the amount of 
   83: processing on this side.
   84: 
   85: =over 4
   86: 
   87: Input: $courseID, $lastDownloadTime, $c
   88: 
   89: $courseID:  The id of the course
   90: 
   91: $lastDownloadTime:  This is the date stamp for when this information was
   92: last gathered.  If it is set to Not downloaded, it will gather the data
   93: again, though it currently does not remove the old data.
   94: 
   95: $c: The connection class that can determine if the browser has aborted.  It
   96: is used to short circuit this function so that it does not continue to 
   97: get information when there is no need.
   98: 
   99: Output: \%classlist
  100: 
  101: \%classlist: A pointer to a hash containing the following data:
  102: 
  103: -A list of student name:domain (as keys) (known below as $name)
  104: 
  105: -A hash pointer for each student containing lastname, generation, firstname,
  106: middlename, and PID : Key is $name.studentInformation
  107: 
  108: -A hash pointer to each students section data : Key is $name.section
  109: 
  110: -If there was an error in dump, it will be returned in the hash.  See
  111: the error codes for dump in lonnet.  Also, an error key will be 
  112: generated if an abort occurs.
  113: 
  114: =back
  115: 
  116: =cut
  117: 
  118: sub DownloadClasslist {
  119:     my ($courseID, $lastDownloadTime, $c)=@_;
  120:     my ($courseDomain,$courseNumber)=split(/\_/,$courseID);
  121:     my %classlist;
  122: 
  123:     my $modifiedTime = &Apache::lonnet::GetFileTimestamp($courseDomain, $courseNumber,
  124:                                                          'classlist.db', 
  125:                                                          $Apache::lonnet::perlvar{'lonUsersDir'});
  126: 
  127:     # Always download the information if lastDownloadTime is set to
  128:     # Not downloaded, otherwise it is only downloaded if the file
  129:     # has been updated and has a more recent date stamp
  130:     if($lastDownloadTime ne 'Not downloaded' &&
  131:        $lastDownloadTime >= $modifiedTime && $modifiedTime >= 0) {
  132:         # Data is not gathered so return UpToDate as true.  This
  133:         # will be interpreted in ProcessClasslist
  134:         $classlist{'lastDownloadTime'}=time;
  135:         $classlist{'UpToDate'} = 'true';
  136:         return \%classlist;
  137:     }
  138: 
  139:     %classlist=&Apache::lonnet::dump('classlist',$courseDomain, $courseNumber);
  140:     foreach(keys (%classlist)) {
  141:         if(/^(con_lost|error|no_such_host)/i) {
  142:             return \%classlist;
  143:         }
  144:     }
  145: 
  146:     foreach my $name (keys(%classlist)) {
  147:         if(defined($c) && ($c->aborted())) {
  148:             $classlist{'error'}='aborted';
  149:             return \%classlist;
  150:         }
  151: 
  152:         my ($studentName,$studentDomain) = split(/\:/,$name);
  153:         # Download student environment data, specifically the full name and id.
  154:         my %studentInformation=&Apache::lonnet::get('environment',
  155:                                                     ['lastname','generation',
  156:                                                      'firstname','middlename',
  157:                                                      'id'],
  158:                                                     $studentDomain,
  159:                                                     $studentName);
  160:         $classlist{$name.':studentInformation'}=\%studentInformation;
  161: 
  162:         if($c->aborted()) {
  163:             $classlist{'error'}='aborted';
  164:             return \%classlist;
  165:         }
  166: 
  167:         #Section
  168:         my %section=&Apache::lonnet::dump('roles',$studentDomain,$studentName);
  169:         $classlist{$name.':sections'}=\%section;
  170:     }
  171: 
  172:     $classlist{'UpToDate'} = 'false';
  173:     $classlist{'lastDownloadTime'}=time;
  174: 
  175:     return \%classlist;
  176: }
  177: 
  178: =pod
  179: 
  180: =item &DownloadCourseInformation()
  181: 
  182: Dump of all the course information for a single student.  The data can be
  183: pruned by making use of dumps regular expression arguement.  This function
  184: also takes a regular expression which it passes straight through to dump.  
  185: The data is no escaped, because it is done elsewhere.  It also
  186: checks the timestamp of the students course database file and only downloads
  187: if it has been modified since the last download.
  188: 
  189: =over 4
  190: 
  191: Input: $namedata, $courseID, $lastDownloadTime, $WhatIWant
  192: 
  193: $namedata: student name:domain
  194: 
  195: $courseID:  The id of the course
  196: 
  197: $lastDownloadTime:  This is the date stamp for when this information was
  198: last gathered.  If it is set to Not downloaded, it will gather the data
  199: again, though it currently does not remove the old data.
  200: 
  201: $WhatIWant:  Regular expression used to get selected data with dump
  202: 
  203: Output: \%courseData
  204: 
  205: \%courseData:  A hash pointer to the raw data from the students course
  206: database.
  207: 
  208: =back
  209: 
  210: =cut
  211: 
  212: sub DownloadCourseInformation {
  213:     my ($namedata,$courseID,$lastDownloadTime,$WhatIWant)=@_;
  214:     my %courseData;
  215:     my ($name,$domain) = split(/\:/,$namedata);
  216: 
  217:     my $modifiedTime = &Apache::lonnet::GetFileTimestamp($domain, $name,
  218:                                       $courseID.'.db', 
  219:                                       $Apache::lonnet::perlvar{'lonUsersDir'});
  220: 
  221:     if($lastDownloadTime >= $modifiedTime && $modifiedTime >= 0) {
  222:         # Data is not gathered so return UpToDate as true.  This
  223:         # will be interpreted in ProcessClasslist
  224:         $courseData{$namedata.':lastDownloadTime'}=time;
  225:         $courseData{$namedata.':UpToDate'} = 'true';
  226:         return \%courseData;
  227:     }
  228: 
  229:     # Download course data
  230:     if(!defined($WhatIWant)) {
  231:         # set the regular expression to everything by setting it to period
  232:         $WhatIWant = '.';
  233:     }
  234:     %courseData=&Apache::lonnet::dump($courseID, $domain, $name, $WhatIWant);
  235:     $courseData{'UpToDate'} = 'false';
  236:     $courseData{'lastDownloadTime'}=time;
  237: 
  238:     my %newData;
  239:     foreach (keys(%courseData)) {
  240:         # need to have the keys to be prepended with the name:domain of the
  241:         # student to reduce data collision later.
  242:         $newData{$namedata.':'.$_} = $courseData{$_};
  243:     }
  244: 
  245:     return \%newData;
  246: }
  247: 
  248: # ----- END DOWNLOAD INFORMATION ---------------------------------------
  249: 
  250: =pod
  251: 
  252: =head1 PROCESSING FUNCTIONS
  253: 
  254: These functions process all the data for all the students.  Also, they
  255: are the functions that access the cache database for writing the majority of
  256: the time.  The downloading and caching were separated to reduce problems 
  257: with stopping downloading then can not tie hash to database later.
  258: 
  259: =cut
  260: 
  261: # ----- PROCESSING FUNCTIONS ---------------------------------------
  262: 
  263: =pod
  264: 
  265: =item &ProcessTopResourceMap()
  266: 
  267: Trace through the "big hash" created in rat/lonuserstate.pm::loadmap.  
  268: Basically, this function organizes a subset of the data and stores it in
  269: cached data.  The data stored is the problems, sequences, sequence titles,
  270: parts of problems, and their ordering.  Column width information is also 
  271: partially handled here on a per sequence basis.
  272: 
  273: =over 4
  274: 
  275: Input: $cache, $c
  276: 
  277: $cache:  A pointer to a hash to store the information
  278: 
  279: $c:  The connection class used to determine if an abort has been sent to the 
  280: browser
  281: 
  282: Output: A string that contains an error message or "OK" if everything went 
  283: smoothly.
  284: 
  285: =back
  286: 
  287: =cut
  288: 
  289: sub ProcessTopResourceMap {
  290:     my ($cache,$c)=@_;
  291:     my %hash;
  292:     my $fn=$ENV{'request.course.fn'};
  293:     if(-e "$fn.db") {
  294: 	my $tieTries=0;
  295: 	while($tieTries < 3) {
  296:             if($c->aborted()) {
  297:                 return;
  298:             }
  299: 	    if(tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) {
  300: 		last;
  301: 	    }
  302: 	    $tieTries++;
  303: 	    sleep 1;
  304: 	}
  305: 	if($tieTries >= 3) {
  306:             return 'Coursemap undefined.';
  307:         }
  308:     } else {
  309:         return 'Can not open Coursemap.';
  310:     }
  311: 
  312:     my $oldkeys;
  313:     if(defined($cache->{'ResourceKeys'})) {
  314:         $oldkeys = $cache->{'ResourceKeys'};
  315:         foreach (split(':::', $cache->{'ResourceKeys'})) {
  316:             delete $cache->{$_};
  317:         }
  318:         delete $cache->{'ResourceKeys'};
  319:     }
  320: 
  321:     # Initialize state machine.  Set information pointing to top level map.
  322:     my (@sequences, @currentResource, @finishResource);
  323:     my ($currentSequence, $currentResourceID, $lastResourceID);
  324: 
  325:     $currentResourceID=$hash{'ids_/res/'.$ENV{'request.course.uri'}};
  326:     push(@currentResource, $currentResourceID);
  327:     $lastResourceID=-1;
  328:     $currentSequence=-1;
  329:     my $topLevelSequenceNumber = $currentSequence;
  330: 
  331:     my %sequenceRecord;
  332:     my %allkeys;
  333:     while(1) {
  334:         if($c->aborted()) {
  335:             last;
  336:         }
  337: 	# HANDLE NEW SEQUENCE!
  338: 	#if page || sequence
  339: 	if(defined($hash{'map_pc_'.$hash{'src_'.$currentResourceID}}) &&
  340:            !defined($sequenceRecord{$currentResourceID})) {
  341:             $sequenceRecord{$currentResourceID}++;
  342: 	    push(@sequences, $currentSequence);
  343: 	    push(@currentResource, $currentResourceID);
  344: 	    push(@finishResource, $lastResourceID);
  345: 
  346: 	    $currentSequence=$hash{'map_pc_'.$hash{'src_'.$currentResourceID}};
  347: 
  348:             # Mark sequence as containing problems.  If it doesn't, then
  349:             # it will be removed when processing for this sequence is
  350:             # complete.  This allows the problems in a sequence
  351:             # to be outputed before problems in the subsequences
  352:             if(!defined($cache->{'orderedSequences'})) {
  353:                 $cache->{'orderedSequences'}=$currentSequence;
  354:             } else {
  355:                 $cache->{'orderedSequences'}.=':'.$currentSequence;
  356:             }
  357:             $allkeys{'orderedSequences'}++;
  358: 
  359: 	    $lastResourceID=$hash{'map_finish_'.
  360: 				  $hash{'src_'.$currentResourceID}};
  361: 	    $currentResourceID=$hash{'map_start_'.
  362: 				     $hash{'src_'.$currentResourceID}};
  363: 
  364: 	    if(!($currentResourceID) || !($lastResourceID)) {
  365: 		$currentSequence=pop(@sequences);
  366: 		$currentResourceID=pop(@currentResource);
  367: 		$lastResourceID=pop(@finishResource);
  368: 		if($currentSequence eq $topLevelSequenceNumber) {
  369: 		    last;
  370: 		}
  371: 	    }
  372:             next;
  373: 	}
  374: 
  375: 	# Handle gradable resources: exams, problems, etc
  376: 	$currentResourceID=~/(\d+)\.(\d+)/;
  377:         my $partA=$1;
  378:         my $partB=$2;
  379: 	if($hash{'src_'.$currentResourceID}=~
  380: 	   /\.(problem|exam|quiz|assess|survey|form)$/ &&
  381: 	   $partA eq $currentSequence && 
  382:            !defined($sequenceRecord{$currentSequence.':'.
  383:                                     $currentResourceID})) {
  384:             $sequenceRecord{$currentSequence.':'.$currentResourceID}++;
  385: 	    my $Problem = &Apache::lonnet::symbclean(
  386: 			  &Apache::lonnet::declutter($hash{'map_id_'.$partA}).
  387: 			  '___'.$partB.'___'.
  388: 			  &Apache::lonnet::declutter($hash{'src_'.
  389: 							 $currentResourceID}));
  390: 
  391: 	    $cache->{$currentResourceID.':problem'}=$Problem;
  392:             $allkeys{$currentResourceID.':problem'}++;
  393: 	    if(!defined($cache->{$currentSequence.':problems'})) {
  394: 		$cache->{$currentSequence.':problems'}=$currentResourceID;
  395: 	    } else {
  396: 		$cache->{$currentSequence.':problems'}.=
  397: 		    ':'.$currentResourceID;
  398: 	    }
  399:             $allkeys{$currentSequence.':problems'}++;
  400: 
  401: 	    my $meta=$hash{'src_'.$currentResourceID};
  402: #            $cache->{$currentResourceID.':title'}=
  403: #                &Apache::lonnet::metdata($meta,'title');
  404:             $cache->{$currentResourceID.':title'}=
  405:                 $hash{'title_'.$currentResourceID};
  406:             $allkeys{$currentResourceID.':title'}++;
  407:             $cache->{$currentResourceID.':source'}=
  408:                 $hash{'src_'.$currentResourceID};
  409:             $allkeys{$currentResourceID.':source'}++;
  410: 
  411:             # Get Parts for problem
  412:             my %beenHere;
  413:             foreach (split(/\,/,&Apache::lonnet::metadata($meta,'packages'))) {
  414:                 if(/^\w+response_\d+.*/) {
  415:                     my (undef, $partId, $responseId) = split(/_/,$_);
  416:                     if($beenHere{'p:'.$partId} ==  0) {
  417:                         $beenHere{'p:'.$partId}++;
  418:                         if(!defined($cache->{$currentSequence.':'.
  419:                                             $currentResourceID.':parts'})) {
  420:                             $cache->{$currentSequence.':'.$currentResourceID.
  421:                                      ':parts'}=$partId;
  422:                         } else {
  423:                             $cache->{$currentSequence.':'.$currentResourceID.
  424:                                      ':parts'}.=':'.$partId;
  425:                         }
  426:                         $allkeys{$currentSequence.':'.$currentResourceID.
  427:                                   ':parts'}++;
  428:                     }
  429:                     if($beenHere{'r:'.$partId.':'.$responseId} == 0) {
  430:                         $beenHere{'r:'.$partId.':'.$responseId}++;
  431:                         if(!defined($cache->{$currentSequence.':'.
  432:                                              $currentResourceID.':'.$partId.
  433:                                              ':responseIDs'})) {
  434:                             $cache->{$currentSequence.':'.$currentResourceID.
  435:                                      ':'.$partId.':responseIDs'}=$responseId;
  436:                         } else {
  437:                             $cache->{$currentSequence.':'.$currentResourceID.
  438:                                      ':'.$partId.':responseIDs'}.=':'.
  439:                                                                   $responseId;
  440:                         }
  441:                         $allkeys{$currentSequence.':'.$currentResourceID.':'.
  442:                                      $partId.':responseIDs'}++;
  443:                     }
  444:                     if(/^optionresponse/ && 
  445:                        $beenHere{'o:'.$partId.':'.$currentResourceID} == 0) {
  446:                         $beenHere{'o:'.$partId.$currentResourceID}++;
  447:                         if(defined($cache->{'OptionResponses'})) {
  448:                             $cache->{'OptionResponses'}.= ':::'.
  449:                                 $currentSequence.':'.$currentResourceID.':'.
  450:                                 $partId.':'.$responseId;
  451:                         } else {
  452:                             $cache->{'OptionResponses'}= $currentSequence.':'.
  453:                                 $currentResourceID.':'.
  454:                                 $partId.':'.$responseId;
  455:                         }
  456:                         $allkeys{'OptionResponses'}++;
  457:                     }
  458:                 }
  459:             }
  460:         }
  461: 
  462: 	# if resource == finish resource, then it is the end of a sequence/page
  463: 	if($currentResourceID eq $lastResourceID) {
  464: 	    # pop off last resource of sequence
  465: 	    $currentResourceID=pop(@currentResource);
  466: 	    $lastResourceID=pop(@finishResource);
  467: 
  468: 	    if(defined($cache->{$currentSequence.':problems'})) {
  469: 		# Capture sequence information here
  470: 		$cache->{$currentSequence.':title'}=
  471: 		    $hash{'title_'.$currentResourceID};
  472:                 $allkeys{$currentSequence.':title'}++;
  473:                 $cache->{$currentSequence.':source'}=
  474:                     $hash{'src_'.$currentResourceID};
  475:                 $allkeys{$currentSequence.':source'}++;
  476: 
  477:                 my $totalProblems=0;
  478:                 foreach my $currentProblem (split(/\:/,
  479:                                                $cache->{$currentSequence.
  480:                                                ':problems'})) {
  481:                     foreach (split(/\:/,$cache->{$currentSequence.':'.
  482:                                                    $currentProblem.
  483:                                                    ':parts'})) {
  484:                         $totalProblems++;
  485:                     }
  486:                 }
  487: 		my @titleLength=split(//,$cache->{$currentSequence.
  488:                                                     ':title'});
  489:                 # $extra is 3 for problems correct and 3 for space
  490:                 # between problems correct and problem output
  491:                 my $extra = 6;
  492: 		if(($totalProblems + $extra) > (scalar @titleLength)) {
  493: 		    $cache->{$currentSequence.':columnWidth'}=
  494:                         $totalProblems + $extra;
  495: 		} else {
  496: 		    $cache->{$currentSequence.':columnWidth'}=
  497:                         (scalar @titleLength);
  498: 		}
  499:                 $allkeys{$currentSequence.':columnWidth'}++;
  500: 	    } else {
  501:                 # Remove sequence from list, if it contains no problems to
  502:                 # display.
  503:                 $cache->{'orderedSequences'}=~s/$currentSequence//;
  504:                 $cache->{'orderedSequences'}=~s/::/:/g;
  505:                 $cache->{'orderedSequences'}=~s/^:|:$//g;
  506:             }
  507: 
  508: 	    $currentSequence=pop(@sequences);
  509: 	    if($currentSequence eq $topLevelSequenceNumber) {
  510: 		last;
  511: 	    }
  512:         }
  513: 
  514: 	# MOVE!!!
  515: 	# move to next resource
  516: 	unless(defined($hash{'to_'.$currentResourceID})) {
  517: 	    # big problem, need to handle.  Next is probably wrong
  518:             my $errorMessage = 'Big problem in ';
  519:             $errorMessage .= 'loncoursedata::ProcessTopLevelMap.';
  520:             $errorMessage .= '  bighash to_$currentResourceID not defined!';
  521:             &Apache::lonnet::logthis($errorMessage);
  522: 	    last;
  523: 	}
  524: 	my @nextResources=();
  525: 	foreach (split(/\,/,$hash{'to_'.$currentResourceID})) {
  526:             if(!defined($sequenceRecord{$currentSequence.':'.
  527:                                         $hash{'goesto_'.$_}})) {
  528:                 push(@nextResources, $hash{'goesto_'.$_});
  529:             }
  530: 	}
  531: 	push(@currentResource, @nextResources);
  532: 	# Set the next resource to be processed
  533: 	$currentResourceID=pop(@currentResource);
  534:     }
  535: 
  536:     my @theKeys = keys(%allkeys);
  537:     my $newkeys = join(':::', @theKeys);
  538:     $cache->{'ResourceKeys'} = join(':::', $newkeys);
  539:     if($newkeys ne $oldkeys) {
  540:         $cache->{'ResourceUpdated'} = 'true';
  541:     } else {
  542:         $cache->{'ResourceUpdated'} = 'false';
  543:     }
  544: 
  545:     unless (untie(%hash)) {
  546:         &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  547:                                  "Could not untie coursemap $fn (browse)".
  548:                                  ".</font>"); 
  549:     }
  550: 
  551:     return 'OK';
  552: }
  553: 
  554: =pod
  555: 
  556: =item &ProcessClasslist()
  557: 
  558: Taking the class list dumped from &DownloadClasslist(), all the 
  559: students and their non-class information is processed using the 
  560: &ProcessStudentInformation() function.  A date stamp is also recorded for
  561: when the data was processed.
  562: 
  563: Takes data downloaded for a student and breaks it up into managable pieces and 
  564: stored in cache data.  The username, domain, class related date, PID, 
  565: full name, and section are all processed here.
  566: 
  567: =over 4
  568: 
  569: Input: $cache, $classlist, $courseID, $ChartDB, $c
  570: 
  571: $cache: A hash pointer to store the data
  572: 
  573: $classlist:  The hash of data collected about a student from 
  574: &DownloadClasslist().  The hash contains a list of students, a pointer 
  575: to a hash of student information for each student, and each students section 
  576: number.
  577: 
  578: $courseID:  The course ID
  579: 
  580: $ChartDB:  The name of the cache database file.
  581: 
  582: $c:  The connection class used to determine if an abort has been sent to the 
  583: browser
  584: 
  585: Output: @names
  586: 
  587: @names:  An array of students whose information has been processed, and are to 
  588: be considered in an arbitrary order.
  589: 
  590: =back
  591: 
  592: =cut
  593: 
  594: sub ProcessClasslist {
  595:     my ($cache,$classlist,$courseID,$c)=@_;
  596:     my @names=();
  597: 
  598:     $cache->{'ClasslistTimeStamp'}=$classlist->{'lastDownloadTime'};
  599:     if($classlist->{'UpToDate'} eq 'true') {
  600:         return split(/:::/,$cache->{'NamesOfStudents'});;
  601:     }
  602: 
  603:     foreach my $name (keys(%$classlist)) {
  604:         if($name =~ /\:section/ || $name =~ /\:studentInformation/ ||
  605:            $name eq '' || $name eq 'UpToDate' || $name eq 'lastDownloadTime') {
  606:             next;
  607:         }
  608:         if($c->aborted()) {
  609:             return ();
  610:         }
  611:         my $studentInformation = $classlist->{$name.':studentInformation'},
  612:         my $sectionData = $classlist->{$name.':sections'},
  613:         my $date = $classlist->{$name},
  614:         my ($studentName,$studentDomain) = split(/\:/,$name);
  615: 
  616:         $cache->{$name.':username'}=$studentName;
  617:         $cache->{$name.':domain'}=$studentDomain;
  618:         # Initialize timestamp for student
  619:         if(!defined($cache->{$name.':lastDownloadTime'})) {
  620:             $cache->{$name.':lastDownloadTime'}='Not downloaded';
  621:             $cache->{$name.':updateTime'}=' Not updated';
  622:         }
  623: 
  624:         my $error = 0;
  625:         foreach(keys(%$studentInformation)) {
  626:             if(/^(con_lost|error|no_such_host)/i) {
  627:                 $cache->{$name.':error'}=
  628:                     'Could not download student environment data.';
  629:                 $cache->{$name.':fullname'}='';
  630:                 $cache->{$name.':id'}='';
  631:                 $error = 1;
  632:             }
  633:         }
  634:         next if($error);
  635:         push(@names,$name);
  636:         $cache->{$name.':fullname'}=&ProcessFullName(
  637:                                           $studentInformation->{'lastname'},
  638:                                           $studentInformation->{'generation'},
  639:                                           $studentInformation->{'firstname'},
  640:                                           $studentInformation->{'middlename'});
  641:         $cache->{$name.':id'}=$studentInformation->{'id'};
  642: 
  643:         my ($end, $start)=split(':',$date);
  644:         $courseID=~s/\_/\//g;
  645:         $courseID=~s/^(\w)/\/$1/;
  646: 
  647:         my $sec='';
  648:         foreach my $key (keys (%$sectionData)) {
  649:             my $value = $sectionData->{$key};
  650:             if ($key=~/^$courseID(?:\/)*(\w+)*\_st$/) {
  651:                 my $tempsection=$1;
  652:                 if($key eq $courseID.'_st') {
  653:                     $tempsection='';
  654:                 }
  655:                 my ($dummy,$roleend,$rolestart)=split(/\_/,$value);
  656:                 if($roleend eq $end && $rolestart eq $start) {
  657:                     $sec = $tempsection;
  658:                     last;
  659:                 }
  660:             }
  661:         }
  662: 
  663:         my $status='Expired';
  664:         if(((!$end) || time < $end) && ((!$start) || (time > $start))) {
  665:             $status='Active';
  666:         }
  667:         $cache->{$name.':Status'}=$status;
  668:         $cache->{$name.':section'}=$sec;
  669: 
  670:         if($sec eq '' || !defined($sec) || $sec eq ' ') {
  671:             $sec = 'none';
  672:         }
  673:         if(defined($cache->{'sectionList'})) {
  674:             if($cache->{'sectionList'} !~ /(^$sec:|^$sec$|:$sec$|:$sec:)/) {
  675:                 $cache->{'sectionList'} .= ':'.$sec;
  676:             }
  677:         } else {
  678:             $cache->{'sectionList'} = $sec;
  679:         }
  680:     }
  681: 
  682:     $cache->{'ClasslistTimestamp'}=time;
  683:     $cache->{'NamesOfStudents'}=join(':::',@names);
  684: 
  685:     return @names;
  686: }
  687: 
  688: =pod
  689: 
  690: =item &ProcessStudentData()
  691: 
  692: Takes the course data downloaded for a student in 
  693: &DownloadCourseInformation() and breaks it up into key value pairs
  694: to be stored in the cached data.  The keys are comprised of the 
  695: $username:$domain:$keyFromCourseDatabase.  The student username:domain is
  696: stored away signifying that the students information has been downloaded and 
  697: can be reused from cached data.
  698: 
  699: =over 4
  700: 
  701: Input: $cache, $courseData, $name
  702: 
  703: $cache: A hash pointer to store data
  704: 
  705: $courseData:  A hash pointer that points to the course data downloaded for a 
  706: student.
  707: 
  708: $name:  username:domain
  709: 
  710: Output: None
  711: 
  712: *NOTE:  There is no output, but an error message is stored away in the cache 
  713: data.  This is checked in &FormatStudentData().  The key username:domain:error 
  714: will only exist if an error occured.  The error is an error from 
  715: &DownloadCourseInformation().
  716: 
  717: =back
  718: 
  719: =cut
  720: 
  721: sub ProcessStudentData {
  722:     my ($cache,$courseData,$name)=@_;
  723: 
  724:     if(!&CheckDateStampError($courseData, $cache, $name)) {
  725:         return;
  726:     }
  727: 
  728:     # This little delete thing, should not be here.  Move some other
  729:     # time though.
  730:     if(defined($cache->{$name.':keys'})) {
  731: 	foreach (split(':::', $cache->{$name.':keys'})) {
  732: 	    delete $cache->{$name.':'.$_};
  733: 	}
  734:         delete $cache->{$name.':keys'};
  735:     }
  736: 
  737:     my %courseKeys;
  738:     # user name:domain was prepended earlier in DownloadCourseInformation
  739:     foreach (keys %$courseData) {
  740: 	my $currentKey =~ s/^$name//;
  741: 	$courseKeys{$currentKey}++;
  742:         $cache->{$_}=$courseData->{$_};
  743:     }
  744: 
  745:     $cache->{$name.':keys'} = join(':::', keys(%courseKeys));
  746: 
  747:     return;
  748: }
  749: 
  750: =pod
  751: 
  752: =item &ExtractStudentData()
  753: 
  754: HISTORY: This function originally existed in every statistics module,
  755: and performed different tasks, the had some overlap.  Due to the need
  756: for the data from the different modules, they were combined into
  757: a single function.
  758: 
  759: This function now extracts all the necessary course data for a student
  760: from what was downloaded from their homeserver.  There is some extra
  761: time overhead compared to the ProcessStudentInformation function, but
  762: it would have had to occurred at some point anyways.  This is now
  763: typically called while downloading the data it will process.  It is
  764: the brother function to ProcessStudentInformation.
  765: 
  766: =over 4
  767: 
  768: Input: $input, $output, $data, $name
  769: 
  770: $input: A hash that contains the input data to be processed
  771: 
  772: $output: A hash to contain the processed data
  773: 
  774: $data: A hash containing the information on what is to be
  775: processed and how (basically).
  776: 
  777: $name:  username:domain
  778: 
  779: The input is slightly different here, but is quite simple.
  780: It is currently used where the $input, $output, and $data
  781: can and are often the same hashes, but they do not need
  782: to be.
  783: 
  784: Output: None
  785: 
  786: *NOTE:  There is no output, but an error message is stored away in the cache 
  787: data.  This is checked in &FormatStudentData().  The key username:domain:error 
  788: will only exist if an error occured.  The error is an error from 
  789: &DownloadCourseInformation().
  790: 
  791: =back
  792: 
  793: =cut
  794: 
  795: sub ExtractStudentData {
  796:     my ($input, $output, $data, $name)=@_;
  797: 
  798:     if(!&CheckDateStampError($input, $data, $name)) {
  799:         return;
  800:     }
  801: 
  802:     # This little delete thing, should not be here.  Move some other
  803:     # time though.
  804:     my %allkeys;
  805:     if(defined($output->{$name.':keys'})) {
  806: 	foreach (split(':::', $output->{$name.':keys'})) {
  807: 	    delete $output->{$name.':'.$_};
  808: 	}
  809:         delete $output->{$name.':keys'};
  810:     }
  811: 
  812:     my ($username,$domain)=split(':',$name);
  813: 
  814:     my $Version;
  815:     my $problemsCorrect = 0;
  816:     my $totalProblems   = 0;
  817:     my $problemsSolved  = 0;
  818:     my $numberOfParts   = 0;
  819:     my $totalAwarded    = 0;
  820:     foreach my $sequence (split(':', $data->{'orderedSequences'})) {
  821:         foreach my $problemID (split(':', $data->{$sequence.':problems'})) {
  822:             my $problem = $data->{$problemID.':problem'};
  823:             my $LatestVersion = $input->{$name.':version:'.$problem};
  824: 
  825:             # Output dashes for all the parts of this problem if there
  826:             # is no version information about the current problem.
  827:             $output->{$name.':'.$problemID.':NoVersion'} = 'false';
  828:             $allkeys{$name.':'.$problemID.':NoVersion'}++;
  829:             if(!$LatestVersion) {
  830:                 foreach my $part (split(/\:/,$data->{$sequence.':'.
  831:                                                       $problemID.
  832:                                                       ':parts'})) {
  833:                     $output->{$name.':'.$problemID.':'.$part.':tries'} = 0;
  834:                     $output->{$name.':'.$problemID.':'.$part.':awarded'} = 0;
  835:                     $output->{$name.':'.$problemID.':'.$part.':code'} = ' ';
  836: 		    $allkeys{$name.':'.$problemID.':'.$part.':tries'}++;
  837: 		    $allkeys{$name.':'.$problemID.':'.$part.':awarded'}++;
  838: 		    $allkeys{$name.':'.$problemID.':'.$part.':code'}++;
  839:                     $totalProblems++;
  840:                 }
  841:                 $output->{$name.':'.$problemID.':NoVersion'} = 'true';
  842:                 next;
  843:             }
  844: 
  845:             my %partData=undef;
  846:             # Initialize part data, display skips correctly
  847:             # Skip refers to when a student made no submissions on that
  848:             # part/problem.
  849:             foreach my $part (split(/\:/,$data->{$sequence.':'.
  850:                                                  $problemID.
  851:                                                  ':parts'})) {
  852:                 $partData{$part.':tries'}=0;
  853:                 $partData{$part.':code'}=' ';
  854:                 $partData{$part.':awarded'}=0;
  855:                 $partData{$part.':timestamp'}=0;
  856:                 foreach my $response (split(':', $data->{$sequence.':'.
  857:                                                          $problemID.':'.
  858:                                                          $part.':responseIDs'})) {
  859:                     $partData{$part.':'.$response.':submission'}='';
  860:                 }
  861:             }
  862: 
  863:             # Looping through all the versions of each part, starting with the
  864:             # oldest version.  Basically, it gets the most recent 
  865:             # set of grade data for each part.
  866:             my @submissions = ();
  867: 	    for(my $Version=1; $Version<=$LatestVersion; $Version++) {
  868:                 foreach my $part (split(/\:/,$data->{$sequence.':'.
  869:                                                      $problemID.
  870:                                                      ':parts'})) {
  871: 
  872:                     if(!defined($input->{"$name:$Version:$problem".
  873:                                          ":resource.$part.solved"})) {
  874:                         # No grade for this submission, so skip
  875:                         next;
  876:                     }
  877: 
  878:                     my $tries=0;
  879:                     my $code=' ';
  880:                     my $awarded=0;
  881: 
  882:                     $tries = $input->{$name.':'.$Version.':'.$problem.
  883:                                       ':resource.'.$part.'.tries'};
  884:                     $awarded = $input->{$name.':'.$Version.':'.$problem.
  885:                                         ':resource.'.$part.'.awarded'};
  886: 
  887:                     $partData{$part.':awarded'}=($awarded) ? $awarded : 0;
  888:                     $partData{$part.':tries'}=($tries) ? $tries : 0;
  889: 
  890:                     $partData{$part.':timestamp'}=$input->{$name.':'.$Version.':'.
  891:                                                            $problem.
  892:                                                            ':timestamp'};
  893:                     if(!$input->{$name.':'.$Version.':'.$problem.':resource.'.$part.
  894:                                  '.previous'}) {
  895:                         foreach my $response (split(':',
  896:                                                    $data->{$sequence.':'.
  897:                                                            $problemID.':'.
  898:                                                            $part.':responseIDs'})) {
  899:                             @submissions=($input->{$name.':'.$Version.':'.
  900:                                                    $problem.
  901:                                                    ':resource.'.$part.'.'.
  902:                                                    $response.'.submission'},
  903:                                           @submissions);
  904:                         }
  905:                     }
  906: 
  907:                     my $val = $input->{$name.':'.$Version.':'.$problem.
  908:                                        ':resource.'.$part.'.solved'};
  909:                     if    ($val eq 'correct_by_student')   {$code = '*';} 
  910:                     elsif ($val eq 'correct_by_override')  {$code = '+';}
  911:                     elsif ($val eq 'incorrect_attempted')  {$code = '.';} 
  912:                     elsif ($val eq 'incorrect_by_override'){$code = '-';}
  913:                     elsif ($val eq 'excused')              {$code = 'x';}
  914:                     elsif ($val eq 'ungraded_attempted')   {$code = '#';}
  915:                     else                                   {$code = ' ';}
  916:                     $partData{$part.':code'}=$code;
  917:                 }
  918:             }
  919: 
  920:             foreach my $part (split(/\:/,$data->{$sequence.':'.$problemID.
  921:                                                  ':parts'})) {
  922:                 $output->{$name.':'.$problemID.':'.$part.':wrong'} = 
  923:                     $partData{$part.':tries'};
  924: 		$allkeys{$name.':'.$problemID.':'.$part.':wrong'}++;
  925: 
  926:                 if($partData{$part.':code'} eq '*') {
  927:                     $output->{$name.':'.$problemID.':'.$part.':wrong'}--;
  928:                     $problemsCorrect++;
  929:                 } elsif($partData{$part.':code'} eq '+') {
  930:                     $output->{$name.':'.$problemID.':'.$part.':wrong'}--;
  931:                     $problemsCorrect++;
  932:                 }
  933: 
  934:                 $output->{$name.':'.$problemID.':'.$part.':tries'} = 
  935:                     $partData{$part.':tries'};
  936:                 $output->{$name.':'.$problemID.':'.$part.':code'} =
  937:                     $partData{$part.':code'};
  938:                 $output->{$name.':'.$problemID.':'.$part.':awarded'} =
  939:                     $partData{$part.':awarded'};
  940: 		$allkeys{$name.':'.$problemID.':'.$part.':tries'}++;
  941: 		$allkeys{$name.':'.$problemID.':'.$part.':code'}++;
  942: 		$allkeys{$name.':'.$problemID.':'.$part.':awarded'}++;
  943: 
  944:                 $totalAwarded += $partData{$part.':awarded'};
  945:                 $output->{$name.':'.$problemID.':'.$part.':timestamp'} =
  946:                     $partData{$part.':timestamp'};
  947: 		$allkeys{$name.':'.$problemID.':'.$part.':timestamp'}++;
  948: 
  949:                 foreach my $response (split(':', $data->{$sequence.':'.
  950:                                                          $problemID.':'.
  951:                                                          $part.':responseIDs'})) {
  952:                     $output->{$name.':'.$problemID.':'.$part.':'.$response.
  953:                               ':submission'}=join(':::',@submissions);
  954: 		    $allkeys{$name.':'.$problemID.':'.$part.':'.$response.
  955: 			     ':submission'}++;
  956:                 }
  957: 
  958:                 if($partData{$part.':code'} ne 'x') {
  959:                     $totalProblems++;
  960:                 }
  961:             }
  962:         }
  963: 
  964:         $output->{$name.':'.$sequence.':problemsCorrect'} = $problemsCorrect;
  965: 	$allkeys{$name.':'.$sequence.':problemsCorrect'}++;
  966:         $problemsSolved += $problemsCorrect;
  967: 	$problemsCorrect=0;
  968:     }
  969: 
  970:     $output->{$name.':problemsSolved'} = $problemsSolved;
  971:     $output->{$name.':totalProblems'} = $totalProblems;
  972:     $output->{$name.':totalAwarded'} = $totalAwarded;
  973:     $allkeys{$name.':problemsSolved'}++;
  974:     $allkeys{$name.':totalProblems'}++;
  975:     $allkeys{$name.':totalAwarded'}++;
  976: 
  977:     $output->{$name.':keys'} = join(':::', keys(%allkeys));
  978: 
  979:     return;
  980: }
  981: 
  982: sub LoadDiscussion {
  983:     my ($courseID)=@_;
  984:     my %Discuss=();
  985:     my %contrib=&Apache::lonnet::dump(
  986:                 $courseID,
  987:                 $ENV{'course.'.$courseID.'.domain'},
  988:                 $ENV{'course.'.$courseID.'.num'});
  989: 				 
  990:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
  991: 
  992:     foreach my $temp(keys %contrib) {
  993: 	if ($temp=~/^version/) {
  994: 	    my $ver=$contrib{$temp};
  995: 	    my ($dummy,$prb)=split(':',$temp);
  996: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
  997: 		my $name=$contrib{"$idx:$prb:sendername"};
  998: 		$Discuss{"$name:$prb"}=$idx;	
  999: 	    }
 1000: 	}
 1001:     }       
 1002: 
 1003:     return \%Discuss;
 1004: }
 1005: 
 1006: # ----- END PROCESSING FUNCTIONS ---------------------------------------
 1007: 
 1008: =pod
 1009: 
 1010: =head1 HELPER FUNCTIONS
 1011: 
 1012: These are just a couple of functions do various odd and end 
 1013: jobs.  There was also a couple of bulk functions added.  These are
 1014: &DownloadStudentCourseData(), &DownloadStudentCourseDataSeparate(), and
 1015: &CheckForResidualDownload().  These functions now act as the interface
 1016: for downloading student course data.  The statistical modules should
 1017: no longer make the calls to dump and download and process etc.  They
 1018: make calls to these bulk functions to get their data.
 1019: 
 1020: =cut
 1021: 
 1022: # ----- HELPER FUNCTIONS -----------------------------------------------
 1023: 
 1024: sub CheckDateStampError {
 1025:     my ($courseData, $cache, $name)=@_;
 1026:     if($courseData->{$name.':UpToDate'} eq 'true') {
 1027:         $cache->{$name.':lastDownloadTime'} = 
 1028:             $courseData->{$name.':lastDownloadTime'};
 1029:         if($courseData->{$name.':lastDownloadTime'} eq 'Not downloaded') {
 1030:             $cache->{$name.':updateTime'} = ' Not updated';
 1031:         } else {
 1032:             $cache->{$name.':updateTime'}=
 1033:                 localtime($courseData->{$name.':lastDownloadTime'});
 1034:         }
 1035:         return 0;
 1036:     }
 1037: 
 1038:     $cache->{$name.':lastDownloadTime'}=$courseData->{$name.':lastDownloadTime'};
 1039:     if($courseData->{$name.':lastDownloadTime'} eq 'Not downloaded') {
 1040:         $cache->{$name.':updateTime'} = ' Not updated';
 1041:     } else {
 1042:         $cache->{$name.':updateTime'}=
 1043:             localtime($courseData->{$name.':lastDownloadTime'});
 1044:     }
 1045: 
 1046:     if(defined($courseData->{$name.':error'})) {
 1047:         $cache->{$name.':error'}=$courseData->{$name.':error'};
 1048:         return 0;
 1049:     }
 1050: 
 1051:     return 1;
 1052: }
 1053: 
 1054: =pod
 1055: 
 1056: =item &ProcessFullName()
 1057: 
 1058: Takes lastname, generation, firstname, and middlename (or some partial
 1059: set of this data) and returns the full name version as a string.  Format
 1060: is Lastname generation, firstname middlename or a subset of this.
 1061: 
 1062: =cut
 1063: 
 1064: sub ProcessFullName {
 1065:     my ($lastname, $generation, $firstname, $middlename)=@_;
 1066:     my $Str = '';
 1067: 
 1068:     if($lastname ne '') {
 1069: 	$Str .= $lastname.' ';
 1070: 	if($generation ne '') {
 1071: 	    $Str .= $generation;
 1072: 	} else {
 1073: 	    chop($Str);
 1074: 	}
 1075: 	$Str .= ', ';
 1076: 	if($firstname ne '') {
 1077: 	    $Str .= $firstname.' ';
 1078: 	}
 1079: 	if($middlename ne '') {
 1080: 	    $Str .= $middlename;
 1081: 	} else {
 1082: 	    chop($Str);
 1083: 	    if($firstname eq '') {
 1084: 		chop($Str);
 1085: 	    }
 1086: 	}
 1087:     } else {
 1088: 	if($firstname ne '') {
 1089: 	    $Str .= $firstname.' ';
 1090: 	}
 1091: 	if($middlename ne '') {
 1092: 	    $Str .= $middlename.' ';
 1093: 	}
 1094: 	if($generation ne '') {
 1095: 	    $Str .= $generation;
 1096: 	} else {
 1097: 	    chop($Str);
 1098: 	}
 1099:     }
 1100: 
 1101:     return $Str;
 1102: }
 1103: 
 1104: =pod
 1105: 
 1106: =item &TestCacheData()
 1107: 
 1108: Determine if the cache database can be accessed with a tie.  It waits up to
 1109: ten seconds before returning failure.  This function exists to help with
 1110: the problems with stopping the data download.  When an abort occurs and the
 1111: user quickly presses a form button and httpd child is created.  This
 1112: child needs to wait for the other to finish (hopefully within ten seconds).
 1113: 
 1114: =over 4
 1115: 
 1116: Input: $ChartDB
 1117: 
 1118: $ChartDB: The name of the cache database to be opened
 1119: 
 1120: Output: -1, 0, 1
 1121: 
 1122: -1: Could not tie database
 1123:  0: Use cached data
 1124:  1: New cache database created, use that.
 1125: 
 1126: =back
 1127: 
 1128: =cut
 1129: 
 1130: sub TestCacheData {
 1131:     my ($ChartDB,$isRecalculate,$totalDelay)=@_;
 1132:     my $isCached=-1;
 1133:     my %testData;
 1134:     my $tieTries=0;
 1135: 
 1136:     if(!defined($totalDelay)) {
 1137:         $totalDelay = 10;
 1138:     }
 1139: 
 1140:     if ((-e "$ChartDB") && (!$isRecalculate)) {
 1141: 	$isCached = 1;
 1142:     } else {
 1143: 	$isCached = 0;
 1144:     }
 1145: 
 1146:     while($tieTries < $totalDelay) {
 1147:         my $result=0;
 1148:         if($isCached) {
 1149:             $result=tie(%testData,'GDBM_File',$ChartDB,&GDBM_READER(),0640);
 1150:         } else {
 1151:             $result=tie(%testData,'GDBM_File',$ChartDB,&GDBM_NEWDB(),0640);
 1152:         }
 1153:         if($result) {
 1154:             last;
 1155:         }
 1156:         $tieTries++;
 1157:         sleep 1;
 1158:     }
 1159:     if($tieTries >= $totalDelay) {
 1160:         return -1;
 1161:     }
 1162: 
 1163:     untie(%testData);
 1164: 
 1165:     return $isCached;
 1166: }
 1167: 
 1168: sub DownloadStudentCourseData {
 1169:     my ($students,$checkDate,$cacheDB,$extract,$status,$courseID,$r,$c)=@_;
 1170: 
 1171:     my $title = 'LON-CAPA Statistics';
 1172:     my $heading = 'Download and Process Course Data';
 1173:     my $studentCount = scalar(@$students);
 1174: 
 1175:     my $WhatIWant;
 1176:     $WhatIWant = '(^version:|';
 1177:     $WhatIWant .= '^\d+:.+?:(resource\.\d+\.';
 1178:     $WhatIWant .= '(solved|tries|previous|awarded|(\d+\.submission))\s*$';
 1179:     $WhatIWant .= '|timestamp)';
 1180:     $WhatIWant .= ')';
 1181: #    $WhatIWant = '.';
 1182: 
 1183:     if($status eq 'true') {
 1184:         &Apache::lonhtmlcommon::Create_PrgWin($r, $title, $heading);
 1185:     }
 1186: 
 1187:     my $displayString;
 1188:     my $count=0;
 1189:     foreach (@$students) {
 1190:         my %cache;
 1191: 
 1192:         if($c->aborted()) { return 'Aborted'; }
 1193: 
 1194:         if($status eq 'true') {
 1195:             $count++;
 1196:             my $displayString = $count.'/'.$studentCount.': '.$_;
 1197:             &Apache::lonhtmlcommon::Update_PrgWin($displayString, $r);
 1198:         }
 1199: 
 1200:         my $downloadTime='Not downloaded';
 1201:         my $needUpdate = 'false';
 1202:         if($checkDate eq 'true'  && 
 1203:            tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER(),0640)) {
 1204:             $downloadTime = $cache{$_.':lastDownloadTime'};
 1205:             $needUpdate = $cache{'ResourceUpdated'};
 1206:             untie(%cache);
 1207:         }
 1208: 
 1209:         if($c->aborted()) { return 'Aborted'; }
 1210: 
 1211:         if($needUpdate eq 'true') {
 1212:             $downloadTime = 'Not downloaded';
 1213: 	}
 1214: 	my $courseData = 
 1215: 	    &DownloadCourseInformation($_, $courseID, $downloadTime, 
 1216: 				       $WhatIWant);
 1217: 	if(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT(),0640)) {
 1218: 	    foreach my $key (keys(%$courseData)) {
 1219: 		if($key =~ /^(con_lost|error|no_such_host)/i) {
 1220: 		    $courseData->{$_.':error'} = 'No course data for '.$_;
 1221: 		    last;
 1222: 		}
 1223: 	    }
 1224: 	    if($extract eq 'true') {
 1225: 		&ExtractStudentData($courseData, \%cache, \%cache, $_);
 1226: 	    } else {
 1227: 		&ProcessStudentData(\%cache, $courseData, $_);
 1228: 	    }
 1229: 	    untie(%cache);
 1230: 	} else {
 1231: 	    next;
 1232: 	}
 1233:     }
 1234:     if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r); }
 1235: 
 1236:     return 'OK';
 1237: }
 1238: 
 1239: sub DownloadStudentCourseDataSeparate {
 1240:     my ($students,$checkDate,$cacheDB,$extract,$status,$courseID,$r,$c)=@_;
 1241:     my $residualFile = '/home/httpd/perl/tmp/'.$courseID.'DownloadFile.db';
 1242:     my $title = 'LON-CAPA Statistics';
 1243:     my $heading = 'Download Course Data';
 1244: 
 1245:     my $WhatIWant;
 1246:     $WhatIWant = '(^version:|';
 1247:     $WhatIWant .= '^\d+:.+?:(resource\.\d+\.';
 1248:     $WhatIWant .= '(solved|tries|previous|awarded|(\d+\.submission))\s*$';
 1249:     $WhatIWant .= '|timestamp)';
 1250:     $WhatIWant .= ')';
 1251: 
 1252:     &CheckForResidualDownload($courseID, $cacheDB, $students, $c);
 1253: 
 1254:     my $studentCount = scalar(@$students);
 1255:     if($status eq 'true') {
 1256:         &Apache::lonhtmlcommon::Create_PrgWin($r, $title, $heading);
 1257:     }
 1258:     my $count=0;
 1259:     my $displayString='';
 1260:     foreach (@$students) {
 1261:         if($c->aborted()) {
 1262:             return 'Aborted';
 1263:         }
 1264: 
 1265:         if($status eq 'true') {
 1266:             $count++;
 1267:             $displayString = $count.'/'.$studentCount.': '.$_;
 1268:             &Apache::lonhtmlcommon::Update_PrgWin($displayString, $r);
 1269:         }
 1270: 
 1271:         my %cache;
 1272:         my $downloadTime='Not downloaded';
 1273:         my $needUpdate = 'false';
 1274:         if($checkDate eq 'true'  && 
 1275:            tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER(),0640)) {
 1276:             $downloadTime = $cache{$_.':lastDownloadTime'};
 1277:             $needUpdate = $cache{'ResourceUpdated'};
 1278:             untie(%cache);
 1279:         }
 1280: 
 1281:         if($c->aborted()) {
 1282:             return 'Aborted';
 1283:         }
 1284: 
 1285:         if($needUpdate eq 'true') {
 1286:             $downloadTime = 'Not downloaded';
 1287: 	}
 1288: 
 1289:         my $error = 0;
 1290:         my $courseData = 
 1291:             &DownloadCourseInformation($_, $courseID, $downloadTime,
 1292:                                        $WhatIWant);
 1293:         my %downloadData;
 1294:         unless(tie(%downloadData,'GDBM_File',$residualFile,
 1295:                    &GDBM_WRCREAT(),0640)) {
 1296:             return 'Failed to tie temporary download hash.';
 1297:         }
 1298:         foreach my $key (keys(%$courseData)) {
 1299:             $downloadData{$key} = $courseData->{$key};
 1300:             if($key =~ /^(con_lost|error|no_such_host)/i) {
 1301:                 $error = 1;
 1302:                 last;
 1303:             }
 1304:         }
 1305:         if($error) {
 1306:             foreach my $deleteKey (keys(%$courseData)) {
 1307:                 delete $downloadData{$deleteKey};
 1308:             }
 1309:             $downloadData{$_.':error'} = 'No course data for '.$_;
 1310:         }
 1311:         untie(%downloadData);
 1312:     }
 1313:     if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r); }
 1314: 
 1315:     return &CheckForResidualDownload($cacheDB, 'true', 'true', 
 1316:                                      $courseID, $r, $c);
 1317: }
 1318: 
 1319: sub CheckForResidualDownload {
 1320:     my ($cacheDB,$extract,$status,$courseID,$r,$c)=@_;
 1321: 
 1322:     my $residualFile = '/home/httpd/perl/tmp/'.$courseID.'DownloadFile.db';
 1323:     if(!-e $residualFile) {
 1324:         return 'OK';
 1325:     }
 1326: 
 1327:     my %downloadData;
 1328:     my %cache;
 1329:     unless(tie(%downloadData,'GDBM_File',$residualFile,&GDBM_READER(),0640)) {
 1330:         return 'Can not tie database for check for residual download: tempDB';
 1331:     }
 1332:     unless(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT(),0640)) {
 1333:         untie(%downloadData);
 1334:         return 'Can not tie database for check for residual download: cacheDB';
 1335:     }
 1336: 
 1337:     my @students=();
 1338:     my %checkStudent;
 1339:     my $key;
 1340:     while(($key, undef) = each %downloadData) {
 1341:         my @temp = split(':', $key);
 1342:         my $student = $temp[0].':'.$temp[1];
 1343:         if(!defined($checkStudent{$student})) {
 1344:             $checkStudent{$student}++;
 1345:             push(@students, $student);
 1346:         }
 1347:     }
 1348: 
 1349:     my $heading = 'Process Course Data';
 1350:     my $title = 'LON-CAPA Statistics';
 1351:     my $studentCount = scalar(@students);
 1352:     if($status eq 'true') {
 1353:         &Apache::lonhtmlcommon::Create_PrgWin($r, $title, $heading);
 1354:     }
 1355: 
 1356:     my $count=1;
 1357:     foreach my $name (@students) {
 1358:         last if($c->aborted());
 1359: 
 1360:         if($status eq 'true') {
 1361:             my $displayString = $count.'/'.$studentCount.': '.$name;
 1362:             &Apache::lonhtmlcommon::Update_PrgWin($displayString, $r);
 1363:         }
 1364: 
 1365:         if($extract eq 'true') {
 1366:             &ExtractStudentData(\%downloadData, \%cache, \%cache, $name);
 1367:         } else {
 1368:             &ProcessStudentData(\%cache, \%downloadData, $name);
 1369:         }
 1370:         $count++;
 1371:     }
 1372: 
 1373:     if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r); }
 1374: 
 1375:     untie(%cache);
 1376:     untie(%downloadData);
 1377: 
 1378:     if(!$c->aborted()) {
 1379:         my @files = ($residualFile);
 1380:         unlink(@files);
 1381:     }
 1382: 
 1383:     return 'OK';
 1384: }
 1385: 
 1386: # ----- END HELPER FUNCTIONS --------------------------------------------
 1387: 
 1388: 1;
 1389: __END__

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