File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.48: download - view: text, annotated - select for diffs
Fri Feb 14 21:45:19 2003 UTC (21 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
&get_current_state() now uses DIFFERENT keys to store different information
instead of using THE SAME KEY EVERY TIME it stores anything for a student.
Most errors seem to be caused by something between my chair and my keyboard.

    1: # The LearningOnline Network with CAPA
    2: # (Publication Handler
    3: #
    4: # $Id: loncoursedata.pm,v 1.48 2003/02/14 21:45:19 matthew 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;
  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 ne 'Not downloaded' && 
  222:        $lastDownloadTime >= $modifiedTime && $modifiedTime >= 0) {
  223:         # Data is not gathered so return UpToDate as true.  This
  224:         # will be interpreted in ProcessClasslist
  225:         $courseData{$namedata.':lastDownloadTime'}=time;
  226:         $courseData{$namedata.':UpToDate'} = 'true';
  227:         return \%courseData;
  228:     }
  229: 
  230:     # Download course data
  231:     if(!defined($WhatIWant)) {
  232:         # set the regular expression to everything by setting it to period
  233:         $WhatIWant = '.';
  234:     }
  235:     %courseData=&Apache::lonnet::dump($courseID, $domain, $name, $WhatIWant);
  236:     $courseData{'UpToDate'} = 'false';
  237:     $courseData{'lastDownloadTime'}=time;
  238: 
  239:     my %newData;
  240:     foreach (keys(%courseData)) {
  241:         # need to have the keys to be prepended with the name:domain of the
  242:         # student to reduce data collision later.
  243:         $newData{$namedata.':'.$_} = $courseData{$_};
  244:     }
  245: 
  246:     return \%newData;
  247: }
  248: 
  249: # ----- END DOWNLOAD INFORMATION ---------------------------------------
  250: 
  251: =pod
  252: 
  253: =head1 PROCESSING FUNCTIONS
  254: 
  255: These functions process all the data for all the students.  Also, they
  256: are the functions that access the cache database for writing the majority of
  257: the time.  The downloading and caching were separated to reduce problems 
  258: with stopping downloading then can not tie hash to database later.
  259: 
  260: =cut
  261: 
  262: # ----- PROCESSING FUNCTIONS ---------------------------------------
  263: 
  264: 
  265: 
  266: =pod
  267: 
  268: =item &get_sequence_assessment_data()
  269: 
  270: AT THIS TIME THE USE OF THIS FUNCTION IS *NOT* RECOMMENDED
  271: 
  272: Use lonnavmaps to build a data structure describing the order and 
  273: assessment contents of each sequence in the current course.
  274: 
  275: The returned structure is a hash reference. 
  276: 
  277: { title  => 'title',
  278:   symb   => 'symb',
  279:   source => '/s/o/u/r/c/e',
  280:   type  => (container|assessment),
  281:   contents     => [ {},{},{},{} ], # only for container
  282:   parts        => [11,13,15],      # only for assessment
  283:   response_ids => [12,14,16]       # only for assessment
  284: }
  285: 
  286: $hash->{'contents'} is a reference to an array of hashes of the same structure.
  287: 
  288: =cut
  289: 
  290: sub get_sequence_assessment_data {
  291:     return undef;
  292:     my $fn=$ENV{'request.course.fn'};
  293:     &Apache::lonnet::logthis('filename = '.$fn);
  294:     ##
  295:     ## use navmaps
  296:     my $navmap = Apache::lonnavmaps::navmap->new($fn.".db",$fn."_parms.db",
  297:                                                  1,0);
  298:     if (!defined($navmap)) {
  299:         return 'Can not open Coursemap';
  300:     }
  301:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  302:     ##
  303:     ## Prime the pump 
  304:     ## 
  305:     ## We are going to loop until we run out of sequences/pages to explore for
  306:     ## resources.  This means we have to start out with something to look
  307:     ## at.
  308:     my $curRes = $iterator->next(); # BEGIN_MAP
  309:     $curRes = $iterator->next(); # The sequence itself
  310:     #
  311:     my $title = $curRes->title();
  312:     my $symb  = $curRes->symb();
  313:     my $src   = $curRes->src();
  314:     #
  315:     my @Nested_Sequences = ();   # Stack of sequences, keeps track of depth
  316:     my $top = { title    => $title,
  317:                 symb     => $symb,
  318:                 type     => 'container',
  319:                 num_assess => 0,
  320:                 contents   => [], };
  321:     push (@Nested_Sequences, $top);
  322:     #
  323:     # We need to keep track of which sequences contain homework problems
  324:     # 
  325:     while (scalar(@Nested_Sequences)) {
  326:         $curRes = $iterator->next();
  327:         my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
  328:         if ($curRes == $iterator->BEGIN_MAP()) {
  329:             # get the map itself, instead of BEGIN_MAP
  330:             $curRes = $iterator->next(); 
  331:             $title = $curRes->title();
  332:             $symb  = $curRes->symb();
  333:             $src   = $curRes->src();
  334:             my $newmap = { title    => $title,
  335:                            src      => $src,
  336:                            symb     => $symb,
  337:                            type     => 'container',
  338:                            num_assess => 0,
  339:                            contents   => [],
  340:                        };
  341:             push (@{$currentmap->{'contents'}},$newmap); # this is permanent
  342:             push (@Nested_Sequences, $newmap); # this is a stack
  343:             next;
  344:         }
  345:         if ($curRes == $iterator->END_MAP()) {
  346:             pop(@Nested_Sequences);
  347:             next;
  348:         }
  349:         next if (! ref($curRes));
  350:         next if (! $curRes->is_problem() && !$curRes->randomout);
  351:         # Okay, from here on out we only deal with assessments
  352:         $title = $curRes->title();
  353:         $symb  = $curRes->symb();
  354:         $src   = $curRes->src();
  355:         my $parts = $curRes->parts();
  356:         my $assessment = { title => $title,
  357:                            src   => $src,
  358:                            symb  => $symb,
  359:                            type  => 'assessment',
  360:                        };
  361:         push(@{$currentmap->{'contents'}},$assessment);
  362:         $currentmap->{'num_assess'}++;
  363:     }
  364:     return $top;
  365: }
  366: 
  367: =pod
  368: 
  369: =item &ProcessTopResourceMap()
  370: 
  371: Trace through the "big hash" created in rat/lonuserstate.pm::loadmap.  
  372: Basically, this function organizes a subset of the data and stores it in
  373: cached data.  The data stored is the problems, sequences, sequence titles,
  374: parts of problems, and their ordering.  Column width information is also 
  375: partially handled here on a per sequence basis.
  376: 
  377: =over 4
  378: 
  379: Input: $cache, $c
  380: 
  381: $cache:  A pointer to a hash to store the information
  382: 
  383: $c:  The connection class used to determine if an abort has been sent to the 
  384: browser
  385: 
  386: Output: A string that contains an error message or "OK" if everything went 
  387: smoothly.
  388: 
  389: =back
  390: 
  391: =cut
  392: 
  393: sub ProcessTopResourceMap {
  394:     my ($cache,$c)=@_;
  395:     my %hash;
  396:     my $fn=$ENV{'request.course.fn'};
  397:     if(-e "$fn.db") {
  398: 	my $tieTries=0;
  399: 	while($tieTries < 3) {
  400:             if($c->aborted()) {
  401:                 return;
  402:             }
  403: 	    if(tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) {
  404: 		last;
  405: 	    }
  406: 	    $tieTries++;
  407: 	    sleep 1;
  408: 	}
  409: 	if($tieTries >= 3) {
  410:             return 'Coursemap undefined.';
  411:         }
  412:     } else {
  413:         return 'Can not open Coursemap.';
  414:     }
  415: 
  416:     my $oldkeys;
  417:     delete $cache->{'OptionResponses'};
  418:     if(defined($cache->{'ResourceKeys'})) {
  419:         $oldkeys = $cache->{'ResourceKeys'};
  420:         foreach (split(':::', $cache->{'ResourceKeys'})) {
  421:             delete $cache->{$_};
  422:         }
  423:         delete $cache->{'ResourceKeys'};
  424:     }
  425: 
  426:     # Initialize state machine.  Set information pointing to top level map.
  427:     my (@sequences, @currentResource, @finishResource);
  428:     my ($currentSequence, $currentResourceID, $lastResourceID);
  429: 
  430:     $currentResourceID=$hash{'ids_'.
  431:       &Apache::lonnet::clutter($ENV{'request.course.uri'})};
  432:     push(@currentResource, $currentResourceID);
  433:     $lastResourceID=-1;
  434:     $currentSequence=-1;
  435:     my $topLevelSequenceNumber = $currentSequence;
  436: 
  437:     my %sequenceRecord;
  438:     my %allkeys;
  439:     while(1) {
  440:         if($c->aborted()) {
  441:             last;
  442:         }
  443: 	# HANDLE NEW SEQUENCE!
  444: 	#if page || sequence
  445: 	if(defined($hash{'map_pc_'.$hash{'src_'.$currentResourceID}}) &&
  446:            !defined($sequenceRecord{$currentResourceID})) {
  447:             $sequenceRecord{$currentResourceID}++;
  448: 	    push(@sequences, $currentSequence);
  449: 	    push(@currentResource, $currentResourceID);
  450: 	    push(@finishResource, $lastResourceID);
  451: 
  452: 	    $currentSequence=$hash{'map_pc_'.$hash{'src_'.$currentResourceID}};
  453: 
  454:             # Mark sequence as containing problems.  If it doesn't, then
  455:             # it will be removed when processing for this sequence is
  456:             # complete.  This allows the problems in a sequence
  457:             # to be outputed before problems in the subsequences
  458:             if(!defined($cache->{'orderedSequences'})) {
  459:                 $cache->{'orderedSequences'}=$currentSequence;
  460:             } else {
  461:                 $cache->{'orderedSequences'}.=':'.$currentSequence;
  462:             }
  463:             $allkeys{'orderedSequences'}++;
  464: 
  465: 	    $lastResourceID=$hash{'map_finish_'.
  466: 				  $hash{'src_'.$currentResourceID}};
  467: 	    $currentResourceID=$hash{'map_start_'.
  468: 				     $hash{'src_'.$currentResourceID}};
  469: 
  470: 	    if(!($currentResourceID) || !($lastResourceID)) {
  471: 		$currentSequence=pop(@sequences);
  472: 		$currentResourceID=pop(@currentResource);
  473: 		$lastResourceID=pop(@finishResource);
  474: 		if($currentSequence eq $topLevelSequenceNumber) {
  475: 		    last;
  476: 		}
  477: 	    }
  478:             next;
  479: 	}
  480: 
  481: 	# Handle gradable resources: exams, problems, etc
  482: 	$currentResourceID=~/(\d+)\.(\d+)/;
  483:         my $partA=$1;
  484:         my $partB=$2;
  485: 	if($hash{'src_'.$currentResourceID}=~
  486: 	   /\.(problem|exam|quiz|assess|survey|form)$/ &&
  487: 	   $partA eq $currentSequence && 
  488:            !defined($sequenceRecord{$currentSequence.':'.
  489:                                     $currentResourceID})) {
  490:             $sequenceRecord{$currentSequence.':'.$currentResourceID}++;
  491: 	    my $Problem = &Apache::lonnet::symbclean(
  492: 			  &Apache::lonnet::declutter($hash{'map_id_'.$partA}).
  493: 			  '___'.$partB.'___'.
  494: 			  &Apache::lonnet::declutter($hash{'src_'.
  495: 							 $currentResourceID}));
  496: 
  497: 	    $cache->{$currentResourceID.':problem'}=$Problem;
  498:             $allkeys{$currentResourceID.':problem'}++;
  499: 	    if(!defined($cache->{$currentSequence.':problems'})) {
  500: 		$cache->{$currentSequence.':problems'}=$currentResourceID;
  501: 	    } else {
  502: 		$cache->{$currentSequence.':problems'}.=
  503: 		    ':'.$currentResourceID;
  504: 	    }
  505:             $allkeys{$currentSequence.':problems'}++;
  506: 
  507: 	    my $meta=$hash{'src_'.$currentResourceID};
  508: #            $cache->{$currentResourceID.':title'}=
  509: #                &Apache::lonnet::metdata($meta,'title');
  510:             $cache->{$currentResourceID.':title'}=
  511:                 $hash{'title_'.$currentResourceID};
  512:             $allkeys{$currentResourceID.':title'}++;
  513:             $cache->{$currentResourceID.':source'}=
  514:                 $hash{'src_'.$currentResourceID};
  515:             $allkeys{$currentResourceID.':source'}++;
  516: 
  517:             # Get Parts for problem
  518:             my %beenHere;
  519:             foreach (split(/\,/,&Apache::lonnet::metadata($meta,'packages'))) {
  520:                 if(/^\w+response_\d+.*/) {
  521:                     my (undef, $partId, $responseId) = split(/_/,$_);
  522:                     if($beenHere{'p:'.$partId} ==  0) {
  523:                         $beenHere{'p:'.$partId}++;
  524:                         if(!defined($cache->{$currentSequence.':'.
  525:                                             $currentResourceID.':parts'})) {
  526:                             $cache->{$currentSequence.':'.$currentResourceID.
  527:                                      ':parts'}=$partId;
  528:                         } else {
  529:                             $cache->{$currentSequence.':'.$currentResourceID.
  530:                                      ':parts'}.=':'.$partId;
  531:                         }
  532:                         $allkeys{$currentSequence.':'.$currentResourceID.
  533:                                   ':parts'}++;
  534:                     }
  535:                     if($beenHere{'r:'.$partId.':'.$responseId} == 0) {
  536:                         $beenHere{'r:'.$partId.':'.$responseId}++;
  537:                         if(!defined($cache->{$currentSequence.':'.
  538:                                              $currentResourceID.':'.$partId.
  539:                                              ':responseIDs'})) {
  540:                             $cache->{$currentSequence.':'.$currentResourceID.
  541:                                      ':'.$partId.':responseIDs'}=$responseId;
  542:                         } else {
  543:                             $cache->{$currentSequence.':'.$currentResourceID.
  544:                                      ':'.$partId.':responseIDs'}.=':'.
  545:                                                                   $responseId;
  546:                         }
  547:                         $allkeys{$currentSequence.':'.$currentResourceID.':'.
  548:                                      $partId.':responseIDs'}++;
  549:                     }
  550:                     if(/^optionresponse/ && 
  551:                        $beenHere{'o:'.$partId.':'.$currentResourceID} == 0) {
  552:                         $beenHere{'o:'.$partId.$currentResourceID}++;
  553:                         if(defined($cache->{'OptionResponses'})) {
  554:                             $cache->{'OptionResponses'}.= ':::'.
  555:                                 $currentSequence.':'.$currentResourceID.':'.
  556:                                 $partId.':'.$responseId;
  557:                         } else {
  558:                             $cache->{'OptionResponses'}= $currentSequence.':'.
  559:                                 $currentResourceID.':'.
  560:                                 $partId.':'.$responseId;
  561:                         }
  562:                         $allkeys{'OptionResponses'}++;
  563:                     }
  564:                 }
  565:             }
  566:         }
  567: 
  568: 	# if resource == finish resource, then it is the end of a sequence/page
  569: 	if($currentResourceID eq $lastResourceID) {
  570: 	    # pop off last resource of sequence
  571: 	    $currentResourceID=pop(@currentResource);
  572: 	    $lastResourceID=pop(@finishResource);
  573: 
  574: 	    if(defined($cache->{$currentSequence.':problems'})) {
  575: 		# Capture sequence information here
  576: 		$cache->{$currentSequence.':title'}=
  577: 		    $hash{'title_'.$currentResourceID};
  578:                 $allkeys{$currentSequence.':title'}++;
  579:                 $cache->{$currentSequence.':source'}=
  580:                     $hash{'src_'.$currentResourceID};
  581:                 $allkeys{$currentSequence.':source'}++;
  582: 
  583:                 my $totalProblems=0;
  584:                 foreach my $currentProblem (split(/\:/,
  585:                                                $cache->{$currentSequence.
  586:                                                ':problems'})) {
  587:                     foreach (split(/\:/,$cache->{$currentSequence.':'.
  588:                                                    $currentProblem.
  589:                                                    ':parts'})) {
  590:                         $totalProblems++;
  591:                     }
  592:                 }
  593: 		my @titleLength=split(//,$cache->{$currentSequence.
  594:                                                     ':title'});
  595:                 # $extra is 5 for problems correct and 3 for space
  596:                 # between problems correct and problem output
  597:                 my $extra = 8;
  598: 		if(($totalProblems + $extra) > (scalar @titleLength)) {
  599: 		    $cache->{$currentSequence.':columnWidth'}=
  600:                         $totalProblems + $extra;
  601: 		} else {
  602: 		    $cache->{$currentSequence.':columnWidth'}=
  603:                         (scalar @titleLength);
  604: 		}
  605:                 $allkeys{$currentSequence.':columnWidth'}++;
  606: 	    } else {
  607:                 # Remove sequence from list, if it contains no problems to
  608:                 # display.
  609:                 $cache->{'orderedSequences'}=~s/$currentSequence//;
  610:                 $cache->{'orderedSequences'}=~s/::/:/g;
  611:                 $cache->{'orderedSequences'}=~s/^:|:$//g;
  612:             }
  613: 
  614: 	    $currentSequence=pop(@sequences);
  615: 	    if($currentSequence eq $topLevelSequenceNumber) {
  616: 		last;
  617: 	    }
  618:         }
  619: 
  620: 	# MOVE!!!
  621: 	# move to next resource
  622: 	unless(defined($hash{'to_'.$currentResourceID})) {
  623: 	    # big problem, need to handle.  Next is probably wrong
  624:             my $errorMessage = 'Big problem in ';
  625:             $errorMessage .= 'loncoursedata::ProcessTopLevelMap.';
  626:             $errorMessage .= "  bighash to_$currentResourceID not defined!";
  627:             &Apache::lonnet::logthis($errorMessage);
  628: 	    if (!defined($currentResourceID)) {last;}
  629: 	}
  630: 	my @nextResources=();
  631: 	foreach (split(/\,/,$hash{'to_'.$currentResourceID})) {
  632:             if(!defined($sequenceRecord{$currentSequence.':'.
  633:                                         $hash{'goesto_'.$_}})) {
  634:                 push(@nextResources, $hash{'goesto_'.$_});
  635:             }
  636: 	}
  637: 	push(@currentResource, @nextResources);
  638: 	# Set the next resource to be processed
  639: 	$currentResourceID=pop(@currentResource);
  640:     }
  641: 
  642:     my @theKeys = keys(%allkeys);
  643:     my $newkeys = join(':::', @theKeys);
  644:     $cache->{'ResourceKeys'} = join(':::', $newkeys);
  645:     if($newkeys ne $oldkeys) {
  646:         $cache->{'ResourceUpdated'} = 'true';
  647:     } else {
  648:         $cache->{'ResourceUpdated'} = 'false';
  649:     }
  650: 
  651:     unless (untie(%hash)) {
  652:         &Apache::lonnet::logthis("<font color=blue>WARNING: ".
  653:                                  "Could not untie coursemap $fn (browse)".
  654:                                  ".</font>"); 
  655:     }
  656: 
  657:     return 'OK';
  658: }
  659: 
  660: =pod
  661: 
  662: =item &ProcessClasslist()
  663: 
  664: Taking the class list dumped from &DownloadClasslist(), all the 
  665: students and their non-class information is processed using the 
  666: &ProcessStudentInformation() function.  A date stamp is also recorded for
  667: when the data was processed.
  668: 
  669: Takes data downloaded for a student and breaks it up into managable pieces and 
  670: stored in cache data.  The username, domain, class related date, PID, 
  671: full name, and section are all processed here.
  672: 
  673: =over 4
  674: 
  675: Input: $cache, $classlist, $courseID, $ChartDB, $c
  676: 
  677: $cache: A hash pointer to store the data
  678: 
  679: $classlist:  The hash of data collected about a student from 
  680: &DownloadClasslist().  The hash contains a list of students, a pointer 
  681: to a hash of student information for each student, and each students section 
  682: number.
  683: 
  684: $courseID:  The course ID
  685: 
  686: $ChartDB:  The name of the cache database file.
  687: 
  688: $c:  The connection class used to determine if an abort has been sent to the 
  689: browser
  690: 
  691: Output: @names
  692: 
  693: @names:  An array of students whose information has been processed, and are to 
  694: be considered in an arbitrary order.  The entries in @names are of the form
  695: username:domain.
  696: 
  697: The values in $cache are as follows:
  698: 
  699:  *NOTE: for the following $name implies username:domain
  700:  $name.':error'                  only defined if an error occured.  Value
  701:                                  contains the error message
  702:  $name.':lastDownloadTime'       unconverted time of the last update of a
  703:                                  student\'s course data
  704:  $name.'updateTime'              coverted time of the last update of a 
  705:                                  student\'s course data
  706:  $name.':username'               username of a student
  707:  $name.':domain'                 domain of a student
  708:  $name.':fullname'               full name of a student
  709:  $name.':id'                     PID of a student
  710:  $name.':Status'                 active/expired status of a student
  711:  $name.':section'                section of a student
  712: 
  713: =back
  714: 
  715: =cut
  716: 
  717: sub ProcessClasslist {
  718:     my ($cache,$classlist,$courseID,$c)=@_;
  719:     my @names=();
  720: 
  721:     $cache->{'ClasslistTimeStamp'}=$classlist->{'lastDownloadTime'};
  722:     if($classlist->{'UpToDate'} eq 'true') {
  723:         return split(/:::/,$cache->{'NamesOfStudents'});;
  724:     }
  725: 
  726:     foreach my $name (keys(%$classlist)) {
  727:         if($name =~ /\:section/ || $name =~ /\:studentInformation/ ||
  728:            $name eq '' || $name eq 'UpToDate' || $name eq 'lastDownloadTime') {
  729:             next;
  730:         }
  731:         if($c->aborted()) {
  732:             return ();
  733:         }
  734:         my $studentInformation = $classlist->{$name.':studentInformation'};
  735:         my $date = $classlist->{$name};
  736:         my ($studentName,$studentDomain) = split(/\:/,$name);
  737: 
  738:         $cache->{$name.':username'}=$studentName;
  739:         $cache->{$name.':domain'}=$studentDomain;
  740:         # Initialize timestamp for student
  741:         if(!defined($cache->{$name.':lastDownloadTime'})) {
  742:             $cache->{$name.':lastDownloadTime'}='Not downloaded';
  743:             $cache->{$name.':updateTime'}=' Not updated';
  744:         }
  745: 
  746:         my $error = 0;
  747:         foreach(keys(%$studentInformation)) {
  748:             if(/^(con_lost|error|no_such_host)/i) {
  749:                 $cache->{$name.':error'}=
  750:                     'Could not download student environment data.';
  751:                 $cache->{$name.':fullname'}='';
  752:                 $cache->{$name.':id'}='';
  753:                 $error = 1;
  754:             }
  755:         }
  756:         next if($error);
  757:         push(@names,$name);
  758:         $cache->{$name.':fullname'}=&ProcessFullName(
  759:                                           $studentInformation->{'lastname'},
  760:                                           $studentInformation->{'generation'},
  761:                                           $studentInformation->{'firstname'},
  762:                                           $studentInformation->{'middlename'});
  763:         $cache->{$name.':id'}=$studentInformation->{'id'};
  764: 
  765:         my ($end, $start)=split(':',$date);
  766:         $courseID=~s/\_/\//g;
  767:         $courseID=~s/^(\w)/\/$1/;
  768: 
  769:         my $sec='';
  770:         my $sectionData = $classlist->{$name.':sections'};
  771:         foreach my $key (keys (%$sectionData)) {
  772:             my $value = $sectionData->{$key};
  773:             if ($key=~/^$courseID(?:\/)*(\w+)*\_st$/) {
  774:                 my $tempsection=$1;
  775:                 if($key eq $courseID.'_st') {
  776:                     $tempsection='';
  777:                 }
  778:                 my (undef,$roleend,$rolestart)=split(/\_/,$value);
  779:                 if($roleend eq $end && $rolestart eq $start) {
  780:                     $sec = $tempsection;
  781:                     last;
  782:                 }
  783:             }
  784:         }
  785: 
  786:         my $status='Expired';
  787:         if(((!$end) || time < $end) && ((!$start) || (time > $start))) {
  788:             $status='Active';
  789:         }
  790:         $cache->{$name.':Status'}=$status;
  791:         $cache->{$name.':section'}=$sec;
  792: 
  793:         if($sec eq '' || !defined($sec) || $sec eq ' ') {
  794:             $sec = 'none';
  795:         }
  796:         if(defined($cache->{'sectionList'})) {
  797:             if($cache->{'sectionList'} !~ /(^$sec:|^$sec$|:$sec$|:$sec:)/) {
  798:                 $cache->{'sectionList'} .= ':'.$sec;
  799:             }
  800:         } else {
  801:             $cache->{'sectionList'} = $sec;
  802:         }
  803:     }
  804: 
  805:     $cache->{'ClasslistTimestamp'}=time;
  806:     $cache->{'NamesOfStudents'}=join(':::',@names);
  807: 
  808:     return @names;
  809: }
  810: 
  811: =pod
  812: 
  813: =item &ProcessStudentData()
  814: 
  815: Takes the course data downloaded for a student in 
  816: &DownloadCourseInformation() and breaks it up into key value pairs
  817: to be stored in the cached data.  The keys are comprised of the 
  818: $username:$domain:$keyFromCourseDatabase.  The student username:domain is
  819: stored away signifying that the students information has been downloaded and 
  820: can be reused from cached data.
  821: 
  822: =over 4
  823: 
  824: Input: $cache, $courseData, $name
  825: 
  826: $cache: A hash pointer to store data
  827: 
  828: $courseData:  A hash pointer that points to the course data downloaded for a 
  829: student.
  830: 
  831: $name:  username:domain
  832: 
  833: Output: None
  834: 
  835: *NOTE:  There is no output, but an error message is stored away in the cache 
  836: data.  This is checked in &FormatStudentData().  The key username:domain:error 
  837: will only exist if an error occured.  The error is an error from 
  838: &DownloadCourseInformation().
  839: 
  840: =back
  841: 
  842: =cut
  843: 
  844: sub ProcessStudentData {
  845:     my ($cache,$courseData,$name)=@_;
  846: 
  847:     if(!&CheckDateStampError($courseData, $cache, $name)) {
  848:         return;
  849:     }
  850: 
  851:     # This little delete thing, should not be here.  Move some other
  852:     # time though.
  853:     if(defined($cache->{$name.':keys'})) {
  854: 	foreach (split(':::', $cache->{$name.':keys'})) {
  855: 	    delete $cache->{$name.':'.$_};
  856: 	}
  857:         delete $cache->{$name.':keys'};
  858:     }
  859: 
  860:     my %courseKeys;
  861:     # user name:domain was prepended earlier in DownloadCourseInformation
  862:     foreach (keys %$courseData) {
  863: 	my $currentKey = $_;
  864: 	$currentKey =~ s/^$name//;
  865: 	$courseKeys{$currentKey}++;
  866:         $cache->{$_}=$courseData->{$_};
  867:     }
  868: 
  869:     $cache->{$name.':keys'} = join(':::', keys(%courseKeys));
  870: 
  871:     return;
  872: }
  873: 
  874: =pod
  875: 
  876: =item &ExtractStudentData()
  877: 
  878: HISTORY: This function originally existed in every statistics module,
  879: and performed different tasks, the had some overlap.  Due to the need
  880: for the data from the different modules, they were combined into
  881: a single function.
  882: 
  883: This function now extracts all the necessary course data for a student
  884: from what was downloaded from their homeserver.  There is some extra
  885: time overhead compared to the ProcessStudentInformation function, but
  886: it would have had to occurred at some point anyways.  This is now
  887: typically called while downloading the data it will process.  It is
  888: the brother function to ProcessStudentInformation.
  889: 
  890: =over 4
  891: 
  892: Input: $input, $output, $data, $name
  893: 
  894: $input: A hash that contains the input data to be processed
  895: 
  896: $output: A hash to contain the processed data
  897: 
  898: $data: A hash containing the information on what is to be
  899: processed and how (basically).
  900: 
  901: $name:  username:domain
  902: 
  903: The input is slightly different here, but is quite simple.
  904: It is currently used where the $input, $output, and $data
  905: can and are often the same hashes, but they do not need
  906: to be.
  907: 
  908: Output: None
  909: 
  910: *NOTE:  There is no output, but an error message is stored away in the cache 
  911: data.  This is checked in &FormatStudentData().  The key username:domain:error 
  912: will only exist if an error occured.  The error is an error from 
  913: &DownloadCourseInformation().
  914: 
  915: =back
  916: 
  917: =cut
  918: 
  919: sub ExtractStudentData {
  920:     my ($input, $output, $data, $name)=@_;
  921: 
  922:     if(!&CheckDateStampError($input, $data, $name)) {
  923:         return;
  924:     }
  925: 
  926:     # This little delete thing, should not be here.  Move some other
  927:     # time though.
  928:     my %allkeys;
  929:     if(defined($output->{$name.':keys'})) {
  930: 	foreach (split(':::', $output->{$name.':keys'})) {
  931: 	    delete $output->{$name.':'.$_};
  932: 	}
  933:         delete $output->{$name.':keys'};
  934:     }
  935: 
  936:     my ($username,$domain)=split(':',$name);
  937: 
  938:     my $Version;
  939:     my $problemsCorrect = 0;
  940:     my $totalProblems   = 0;
  941:     my $problemsSolved  = 0;
  942:     my $numberOfParts   = 0;
  943:     my $totalAwarded    = 0;
  944:     foreach my $sequence (split(':', $data->{'orderedSequences'})) {
  945:         foreach my $problemID (split(':', $data->{$sequence.':problems'})) {
  946:             my $problem = $data->{$problemID.':problem'};
  947:             my $LatestVersion = $input->{$name.':version:'.$problem};
  948: 
  949:             # Output dashes for all the parts of this problem if there
  950:             # is no version information about the current problem.
  951:             $output->{$name.':'.$problemID.':NoVersion'} = 'false';
  952:             $allkeys{$name.':'.$problemID.':NoVersion'}++;
  953:             if(!$LatestVersion) {
  954:                 foreach my $part (split(/\:/,$data->{$sequence.':'.
  955:                                                       $problemID.
  956:                                                       ':parts'})) {
  957:                     $output->{$name.':'.$problemID.':'.$part.':tries'} = 0;
  958:                     $output->{$name.':'.$problemID.':'.$part.':awarded'} = 0;
  959:                     $output->{$name.':'.$problemID.':'.$part.':code'} = ' ';
  960: 		    $allkeys{$name.':'.$problemID.':'.$part.':tries'}++;
  961: 		    $allkeys{$name.':'.$problemID.':'.$part.':awarded'}++;
  962: 		    $allkeys{$name.':'.$problemID.':'.$part.':code'}++;
  963:                     $totalProblems++;
  964:                 }
  965:                 $output->{$name.':'.$problemID.':NoVersion'} = 'true';
  966:                 next;
  967:             }
  968: 
  969:             my %partData=undef;
  970:             # Initialize part data, display skips correctly
  971:             # Skip refers to when a student made no submissions on that
  972:             # part/problem.
  973:             foreach my $part (split(/\:/,$data->{$sequence.':'.
  974:                                                  $problemID.
  975:                                                  ':parts'})) {
  976:                 $partData{$part.':tries'}=0;
  977:                 $partData{$part.':code'}=' ';
  978:                 $partData{$part.':awarded'}=0;
  979:                 $partData{$part.':timestamp'}=0;
  980:                 foreach my $response (split(':', $data->{$sequence.':'.
  981:                                                          $problemID.':'.
  982:                                                          $part.':responseIDs'})) {
  983:                     $partData{$part.':'.$response.':submission'}='';
  984:                 }
  985:             }
  986: 
  987:             # Looping through all the versions of each part, starting with the
  988:             # oldest version.  Basically, it gets the most recent 
  989:             # set of grade data for each part.
  990:             my @submissions = ();
  991: 	    for(my $Version=1; $Version<=$LatestVersion; $Version++) {
  992:                 foreach my $part (split(/\:/,$data->{$sequence.':'.
  993:                                                      $problemID.
  994:                                                      ':parts'})) {
  995: 
  996:                     if(!defined($input->{"$name:$Version:$problem".
  997:                                          ":resource.$part.solved"})) {
  998:                         # No grade for this submission, so skip
  999:                         next;
 1000:                     }
 1001: 
 1002:                     my $tries=0;
 1003:                     my $code=' ';
 1004:                     my $awarded=0;
 1005: 
 1006:                     $tries = $input->{$name.':'.$Version.':'.$problem.
 1007:                                       ':resource.'.$part.'.tries'};
 1008:                     $awarded = $input->{$name.':'.$Version.':'.$problem.
 1009:                                         ':resource.'.$part.'.awarded'};
 1010: 
 1011:                     $partData{$part.':awarded'}=($awarded) ? $awarded : 0;
 1012:                     $partData{$part.':tries'}=($tries) ? $tries : 0;
 1013: 
 1014:                     $partData{$part.':timestamp'}=$input->{$name.':'.$Version.':'.
 1015:                                                            $problem.
 1016:                                                            ':timestamp'};
 1017:                     if(!$input->{$name.':'.$Version.':'.$problem.':resource.'.$part.
 1018:                                  '.previous'}) {
 1019:                         foreach my $response (split(':',
 1020:                                                    $data->{$sequence.':'.
 1021:                                                            $problemID.':'.
 1022:                                                            $part.':responseIDs'})) {
 1023:                             @submissions=($input->{$name.':'.$Version.':'.
 1024:                                                    $problem.
 1025:                                                    ':resource.'.$part.'.'.
 1026:                                                    $response.'.submission'},
 1027:                                           @submissions);
 1028:                         }
 1029:                     }
 1030: 
 1031:                     my $val = $input->{$name.':'.$Version.':'.$problem.
 1032:                                        ':resource.'.$part.'.solved'};
 1033:                     if    ($val eq 'correct_by_student')   {$code = '*';} 
 1034:                     elsif ($val eq 'correct_by_override')  {$code = '+';}
 1035:                     elsif ($val eq 'incorrect_attempted')  {$code = '.';} 
 1036:                     elsif ($val eq 'incorrect_by_override'){$code = '-';}
 1037:                     elsif ($val eq 'excused')              {$code = 'x';}
 1038:                     elsif ($val eq 'ungraded_attempted')   {$code = '#';}
 1039:                     else                                   {$code = ' ';}
 1040:                     $partData{$part.':code'}=$code;
 1041:                 }
 1042:             }
 1043: 
 1044:             foreach my $part (split(/\:/,$data->{$sequence.':'.$problemID.
 1045:                                                  ':parts'})) {
 1046:                 $output->{$name.':'.$problemID.':'.$part.':wrong'} = 
 1047:                     $partData{$part.':tries'};
 1048: 		$allkeys{$name.':'.$problemID.':'.$part.':wrong'}++;
 1049: 
 1050:                 if($partData{$part.':code'} eq '*') {
 1051:                     $output->{$name.':'.$problemID.':'.$part.':wrong'}--;
 1052:                     $problemsCorrect++;
 1053:                 } elsif($partData{$part.':code'} eq '+') {
 1054:                     $output->{$name.':'.$problemID.':'.$part.':wrong'}--;
 1055:                     $problemsCorrect++;
 1056:                 }
 1057: 
 1058:                 $output->{$name.':'.$problemID.':'.$part.':tries'} = 
 1059:                     $partData{$part.':tries'};
 1060:                 $output->{$name.':'.$problemID.':'.$part.':code'} =
 1061:                     $partData{$part.':code'};
 1062:                 $output->{$name.':'.$problemID.':'.$part.':awarded'} =
 1063:                     $partData{$part.':awarded'};
 1064: 		$allkeys{$name.':'.$problemID.':'.$part.':tries'}++;
 1065: 		$allkeys{$name.':'.$problemID.':'.$part.':code'}++;
 1066: 		$allkeys{$name.':'.$problemID.':'.$part.':awarded'}++;
 1067: 
 1068:                 $totalAwarded += $partData{$part.':awarded'};
 1069:                 $output->{$name.':'.$problemID.':'.$part.':timestamp'} =
 1070:                     $partData{$part.':timestamp'};
 1071: 		$allkeys{$name.':'.$problemID.':'.$part.':timestamp'}++;
 1072: 
 1073:                 foreach my $response (split(':', $data->{$sequence.':'.
 1074:                                                          $problemID.':'.
 1075:                                                          $part.':responseIDs'})) {
 1076:                     $output->{$name.':'.$problemID.':'.$part.':'.$response.
 1077:                               ':submission'}=join(':::',@submissions);
 1078: 		    $allkeys{$name.':'.$problemID.':'.$part.':'.$response.
 1079: 			     ':submission'}++;
 1080:                 }
 1081: 
 1082:                 if($partData{$part.':code'} ne 'x') {
 1083:                     $totalProblems++;
 1084:                 }
 1085:             }
 1086:         }
 1087: 
 1088:         $output->{$name.':'.$sequence.':problemsCorrect'} = $problemsCorrect;
 1089: 	$allkeys{$name.':'.$sequence.':problemsCorrect'}++;
 1090:         $problemsSolved += $problemsCorrect;
 1091: 	$problemsCorrect=0;
 1092:     }
 1093: 
 1094:     $output->{$name.':problemsSolved'} = $problemsSolved;
 1095:     $output->{$name.':totalProblems'} = $totalProblems;
 1096:     $output->{$name.':totalAwarded'} = $totalAwarded;
 1097:     $allkeys{$name.':problemsSolved'}++;
 1098:     $allkeys{$name.':totalProblems'}++;
 1099:     $allkeys{$name.':totalAwarded'}++;
 1100: 
 1101:     $output->{$name.':keys'} = join(':::', keys(%allkeys));
 1102: 
 1103:     return;
 1104: }
 1105: 
 1106: sub LoadDiscussion {
 1107:     my ($courseID)=@_;
 1108:     my %Discuss=();
 1109:     my %contrib=&Apache::lonnet::dump(
 1110:                 $courseID,
 1111:                 $ENV{'course.'.$courseID.'.domain'},
 1112:                 $ENV{'course.'.$courseID.'.num'});
 1113: 				 
 1114:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
 1115: 
 1116:     foreach my $temp(keys %contrib) {
 1117: 	if ($temp=~/^version/) {
 1118: 	    my $ver=$contrib{$temp};
 1119: 	    my ($dummy,$prb)=split(':',$temp);
 1120: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
 1121: 		my $name=$contrib{"$idx:$prb:sendername"};
 1122: 		$Discuss{"$name:$prb"}=$idx;	
 1123: 	    }
 1124: 	}
 1125:     }       
 1126: 
 1127:     return \%Discuss;
 1128: }
 1129: 
 1130: # ----- END PROCESSING FUNCTIONS ---------------------------------------
 1131: 
 1132: =pod
 1133: 
 1134: =head1 HELPER FUNCTIONS
 1135: 
 1136: These are just a couple of functions do various odd and end 
 1137: jobs.  There was also a couple of bulk functions added.  These are
 1138: &DownloadStudentCourseData(), &DownloadStudentCourseDataSeparate(), and
 1139: &CheckForResidualDownload().  These functions now act as the interface
 1140: for downloading student course data.  The statistical modules should
 1141: no longer make the calls to dump and download and process etc.  They
 1142: make calls to these bulk functions to get their data.
 1143: 
 1144: =cut
 1145: 
 1146: # ----- HELPER FUNCTIONS -----------------------------------------------
 1147: 
 1148: sub CheckDateStampError {
 1149:     my ($courseData, $cache, $name)=@_;
 1150:     if($courseData->{$name.':UpToDate'} eq 'true') {
 1151:         $cache->{$name.':lastDownloadTime'} = 
 1152:             $courseData->{$name.':lastDownloadTime'};
 1153:         if($courseData->{$name.':lastDownloadTime'} eq 'Not downloaded') {
 1154:             $cache->{$name.':updateTime'} = ' Not updated';
 1155:         } else {
 1156:             $cache->{$name.':updateTime'}=
 1157:                 localtime($courseData->{$name.':lastDownloadTime'});
 1158:         }
 1159:         return 0;
 1160:     }
 1161: 
 1162:     $cache->{$name.':lastDownloadTime'}=$courseData->{$name.':lastDownloadTime'};
 1163:     if($courseData->{$name.':lastDownloadTime'} eq 'Not downloaded') {
 1164:         $cache->{$name.':updateTime'} = ' Not updated';
 1165:     } else {
 1166:         $cache->{$name.':updateTime'}=
 1167:             localtime($courseData->{$name.':lastDownloadTime'});
 1168:     }
 1169: 
 1170:     if(defined($courseData->{$name.':error'})) {
 1171:         $cache->{$name.':error'}=$courseData->{$name.':error'};
 1172:         return 0;
 1173:     }
 1174: 
 1175:     return 1;
 1176: }
 1177: 
 1178: =pod
 1179: 
 1180: =item &ProcessFullName()
 1181: 
 1182: Takes lastname, generation, firstname, and middlename (or some partial
 1183: set of this data) and returns the full name version as a string.  Format
 1184: is Lastname generation, firstname middlename or a subset of this.
 1185: 
 1186: =cut
 1187: 
 1188: sub ProcessFullName {
 1189:     my ($lastname, $generation, $firstname, $middlename)=@_;
 1190:     my $Str = '';
 1191: 
 1192:     # Strip whitespace preceeding & following name components.
 1193:     $lastname   =~ s/(\s+$|^\s+)//g;
 1194:     $generation =~ s/(\s+$|^\s+)//g;
 1195:     $firstname  =~ s/(\s+$|^\s+)//g;
 1196:     $middlename =~ s/(\s+$|^\s+)//g;
 1197: 
 1198:     if($lastname ne '') {
 1199: 	$Str .= $lastname;
 1200: 	$Str .= ' '.$generation if ($generation ne '');
 1201: 	$Str .= ',';
 1202:         $Str .= ' '.$firstname  if ($firstname ne '');
 1203:         $Str .= ' '.$middlename if ($middlename ne '');
 1204:     } else {
 1205:         $Str .= $firstname      if ($firstname ne '');
 1206:         $Str .= ' '.$middlename if ($middlename ne '');
 1207:         $Str .= ' '.$generation if ($generation ne '');
 1208:     }
 1209: 
 1210:     return $Str;
 1211: }
 1212: 
 1213: =pod
 1214: 
 1215: =item &TestCacheData()
 1216: 
 1217: Determine if the cache database can be accessed with a tie.  It waits up to
 1218: ten seconds before returning failure.  This function exists to help with
 1219: the problems with stopping the data download.  When an abort occurs and the
 1220: user quickly presses a form button and httpd child is created.  This
 1221: child needs to wait for the other to finish (hopefully within ten seconds).
 1222: 
 1223: =over 4
 1224: 
 1225: Input: $ChartDB
 1226: 
 1227: $ChartDB: The name of the cache database to be opened
 1228: 
 1229: Output: -1, 0, 1
 1230: 
 1231: -1: Could not tie database
 1232:  0: Use cached data
 1233:  1: New cache database created, use that.
 1234: 
 1235: =back
 1236: 
 1237: =cut
 1238: 
 1239: sub TestCacheData {
 1240:     my ($ChartDB,$isRecalculate,$totalDelay)=@_;
 1241:     my $isCached=-1;
 1242:     my %testData;
 1243:     my $tieTries=0;
 1244: 
 1245:     if(!defined($totalDelay)) {
 1246:         $totalDelay = 10;
 1247:     }
 1248: 
 1249:     if ((-e "$ChartDB") && (!$isRecalculate)) {
 1250: 	$isCached = 1;
 1251:     } else {
 1252: 	$isCached = 0;
 1253:     }
 1254: 
 1255:     while($tieTries < $totalDelay) {
 1256:         my $result=0;
 1257:         if($isCached) {
 1258:             $result=tie(%testData,'GDBM_File',$ChartDB,&GDBM_READER(),0640);
 1259:         } else {
 1260:             $result=tie(%testData,'GDBM_File',$ChartDB,&GDBM_NEWDB(),0640);
 1261:         }
 1262:         if($result) {
 1263:             last;
 1264:         }
 1265:         $tieTries++;
 1266:         sleep 1;
 1267:     }
 1268:     if($tieTries >= $totalDelay) {
 1269:         return -1;
 1270:     }
 1271: 
 1272:     untie(%testData);
 1273: 
 1274:     return $isCached;
 1275: }
 1276: 
 1277: sub DownloadStudentCourseData {
 1278:     my ($students,$checkDate,$cacheDB,$extract,$status,$courseID,$r,$c)=@_;
 1279: 
 1280:     my $title = 'LON-CAPA Statistics';
 1281:     my $heading = 'Download and Process Course Data';
 1282:     my $studentCount = scalar(@$students);
 1283: 
 1284:     my $WhatIWant;
 1285:     $WhatIWant = '(^version:|';
 1286:     $WhatIWant .= '^\d+:.+?:(resource\.\d+\.';
 1287:     $WhatIWant .= '(solved|tries|previous|awarded|(\d+\.submission))\s*$';#'
 1288:     $WhatIWant .= '|timestamp)';
 1289:     $WhatIWant .= ')';
 1290: #    $WhatIWant = '.';
 1291: 
 1292:     if($status eq 'true') {
 1293:         &Apache::lonhtmlcommon::Create_PrgWin($r, $title, $heading);
 1294:     }
 1295: 
 1296:     my $displayString;
 1297:     my $count=0;
 1298:     foreach (@$students) {
 1299:         my %cache;
 1300: 
 1301:         if($c->aborted()) { return 'Aborted'; }
 1302: 
 1303:         if($status eq 'true') {
 1304:             $count++;
 1305:             my $displayString = $count.'/'.$studentCount.': '.$_;
 1306:             &Apache::lonhtmlcommon::Update_PrgWin($displayString, $r);
 1307:         }
 1308: 
 1309:         my $downloadTime='Not downloaded';
 1310:         my $needUpdate = 'false';
 1311:         if($checkDate eq 'true'  && 
 1312:            tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER(),0640)) {
 1313:             $downloadTime = $cache{$_.':lastDownloadTime'};
 1314:             $needUpdate = $cache{'ResourceUpdated'};
 1315:             untie(%cache);
 1316:         }
 1317: 
 1318:         if($c->aborted()) { return 'Aborted'; }
 1319: 
 1320:         if($needUpdate eq 'true') {
 1321:             $downloadTime = 'Not downloaded';
 1322: 	}
 1323: 	my $courseData = 
 1324: 	    &DownloadCourseInformation($_, $courseID, $downloadTime, 
 1325: 				       $WhatIWant);
 1326: 	if(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT(),0640)) {
 1327: 	    foreach my $key (keys(%$courseData)) {
 1328: 		if($key =~ /^(con_lost|error|no_such_host)/i) {
 1329: 		    $courseData->{$_.':error'} = 'No course data for '.$_;
 1330: 		    last;
 1331: 		}
 1332: 	    }
 1333: 	    if($extract eq 'true') {
 1334: 		&ExtractStudentData($courseData, \%cache, \%cache, $_);
 1335: 	    } else {
 1336: 		&ProcessStudentData(\%cache, $courseData, $_);
 1337: 	    }
 1338: 	    untie(%cache);
 1339: 	} else {
 1340: 	    next;
 1341: 	}
 1342:     }
 1343:     if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r); }
 1344: 
 1345:     return 'OK';
 1346: }
 1347: 
 1348: sub DownloadStudentCourseDataSeparate {
 1349:     my ($students,$checkDate,$cacheDB,$extract,$status,$courseID,$r,$c)=@_;
 1350:     my $residualFile = $Apache::lonnet::tmpdir.$courseID.'DownloadFile.db';
 1351:     my $title = 'LON-CAPA Statistics';
 1352:     my $heading = 'Download Course Data';
 1353: 
 1354:     my $WhatIWant;
 1355:     $WhatIWant = '(^version:|';
 1356:     $WhatIWant .= '^\d+:.+?:(resource\.\d+\.';
 1357:     $WhatIWant .= '(solved|tries|previous|awarded|(\d+\.submission))\s*$';#'
 1358:     $WhatIWant .= '|timestamp)';
 1359:     $WhatIWant .= ')';
 1360: 
 1361:     &CheckForResidualDownload($cacheDB, 'true', 'true', $courseID, $r, $c);
 1362: 
 1363:     my $studentCount = scalar(@$students);
 1364:     if($status eq 'true') {
 1365:         &Apache::lonhtmlcommon::Create_PrgWin($r, $title, $heading);
 1366:     }
 1367:     my $count=0;
 1368:     my $displayString='';
 1369:     foreach (@$students) {
 1370:         if($c->aborted()) {
 1371:             return 'Aborted';
 1372:         }
 1373: 
 1374:         if($status eq 'true') {
 1375:             $count++;
 1376:             $displayString = $count.'/'.$studentCount.': '.$_;
 1377:             &Apache::lonhtmlcommon::Update_PrgWin($displayString, $r);
 1378:         }
 1379: 
 1380:         my %cache;
 1381:         my $downloadTime='Not downloaded';
 1382:         my $needUpdate = 'false';
 1383:         if($checkDate eq 'true'  && 
 1384:            tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER(),0640)) {
 1385:             $downloadTime = $cache{$_.':lastDownloadTime'};
 1386:             $needUpdate = $cache{'ResourceUpdated'};
 1387:             untie(%cache);
 1388:         }
 1389: 
 1390:         if($c->aborted()) {
 1391:             return 'Aborted';
 1392:         }
 1393: 
 1394:         if($needUpdate eq 'true') {
 1395:             $downloadTime = 'Not downloaded';
 1396: 	}
 1397: 
 1398:         my $error = 0;
 1399:         my $courseData = 
 1400:             &DownloadCourseInformation($_, $courseID, $downloadTime,
 1401:                                        $WhatIWant);
 1402:         my %downloadData;
 1403:         unless(tie(%downloadData,'GDBM_File',$residualFile,
 1404:                    &GDBM_WRCREAT(),0640)) {
 1405:             return 'Failed to tie temporary download hash.';
 1406:         }
 1407:         foreach my $key (keys(%$courseData)) {
 1408:             $downloadData{$key} = $courseData->{$key};
 1409:             if($key =~ /^(con_lost|error|no_such_host)/i) {
 1410:                 $error = 1;
 1411:                 last;
 1412:             }
 1413:         }
 1414:         if($error) {
 1415:             foreach my $deleteKey (keys(%$courseData)) {
 1416:                 delete $downloadData{$deleteKey};
 1417:             }
 1418:             $downloadData{$_.':error'} = 'No course data for '.$_;
 1419:         }
 1420:         untie(%downloadData);
 1421:     }
 1422:     if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r); }
 1423: 
 1424:     return &CheckForResidualDownload($cacheDB, 'true', 'true', 
 1425:                                      $courseID, $r, $c);
 1426: }
 1427: 
 1428: sub CheckForResidualDownload {
 1429:     my ($cacheDB,$extract,$status,$courseID,$r,$c)=@_;
 1430: 
 1431:     my $residualFile = $Apache::lonnet::tmpdir.$courseID.'DownloadFile.db';
 1432:     if(!-e $residualFile) {
 1433:         return 'OK';
 1434:     }
 1435: 
 1436:     my %downloadData;
 1437:     my %cache;
 1438:     unless(tie(%downloadData,'GDBM_File',$residualFile,&GDBM_READER(),0640)) {
 1439:         return 'Can not tie database for check for residual download: tempDB';
 1440:     }
 1441:     unless(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT(),0640)) {
 1442:         untie(%downloadData);
 1443:         return 'Can not tie database for check for residual download: cacheDB';
 1444:     }
 1445: 
 1446:     my @students=();
 1447:     my %checkStudent;
 1448:     my $key;
 1449:     while(($key, undef) = each %downloadData) {
 1450:         my @temp = split(':', $key);
 1451:         my $student = $temp[0].':'.$temp[1];
 1452:         if(!defined($checkStudent{$student})) {
 1453:             $checkStudent{$student}++;
 1454:             push(@students, $student);
 1455:         }
 1456:     }
 1457: 
 1458:     my $heading = 'Process Course Data';
 1459:     my $title = 'LON-CAPA Statistics';
 1460:     my $studentCount = scalar(@students);
 1461:     if($status eq 'true') {
 1462:         &Apache::lonhtmlcommon::Create_PrgWin($r, $title, $heading);
 1463:     }
 1464: 
 1465:     my $count=1;
 1466:     foreach my $name (@students) {
 1467:         last if($c->aborted());
 1468: 
 1469:         if($status eq 'true') {
 1470:             my $displayString = $count.'/'.$studentCount.': '.$name;
 1471:             &Apache::lonhtmlcommon::Update_PrgWin($displayString, $r);
 1472:         }
 1473: 
 1474:         if($extract eq 'true') {
 1475:             &ExtractStudentData(\%downloadData, \%cache, \%cache, $name);
 1476:         } else {
 1477:             &ProcessStudentData(\%cache, \%downloadData, $name);
 1478:         }
 1479:         $count++;
 1480:     }
 1481: 
 1482:     if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r); }
 1483: 
 1484:     untie(%cache);
 1485:     untie(%downloadData);
 1486: 
 1487:     if(!$c->aborted()) {
 1488:         my @files = ($residualFile);
 1489:         unlink(@files);
 1490:     }
 1491: 
 1492:     return 'OK';
 1493: }
 1494: 
 1495: 
 1496: ################################################
 1497: ################################################
 1498: 
 1499: =pod
 1500: 
 1501: =item &make_into_hash($values);
 1502: 
 1503: Returns a reference to a hash as described by $values.  $values is
 1504: assumed to be the result of 
 1505:     join(':',map {&Apache::lonnet::escape($_)} %orighash;
 1506: 
 1507: This is a helper function for get_current_state.
 1508: 
 1509: =cut
 1510: 
 1511: ################################################
 1512: ################################################
 1513: sub make_into_hash {
 1514:     my $values = shift;
 1515:     my %tmp = map { &Apache::lonnet::unescape($_); }
 1516:                                            split(':',$values);
 1517:     return \%tmp;
 1518: }
 1519: 
 1520: 
 1521: ################################################
 1522: ################################################
 1523: 
 1524: =pod
 1525: 
 1526: =item &get_current_state($sname,$sdom,$symb,$courseid);
 1527: 
 1528: Retrieve the current status of a students performance.  $sname and
 1529: $sdom are the only required parameters.  If $symb is undef the results
 1530: of an &Apache::lonnet::currentdump() will be returned.  
 1531: If $courseid is undef it will be retrieved from the environment.
 1532: 
 1533: The return structure is based on &Apache::lonnet::currentdump.  If
 1534: $symb is unspecified, all the students data is returned in a hash of
 1535: the form:
 1536: ( 
 1537:   symb1 => { param1 => value1, param2 => value2 ... },
 1538:   symb2 => { param1 => value1, param2 => value2 ... },
 1539: )
 1540: 
 1541: If $symb is specified, a hash of 
 1542: (
 1543:   param1 => value1, 
 1544:   param2 => value2,
 1545: )
 1546: is returned.
 1547: 
 1548: If no data is found for $symb, or if the student has not performance data,
 1549: an empty list is returned.
 1550: 
 1551: =cut
 1552: 
 1553: ################################################
 1554: ################################################
 1555: sub get_current_state {
 1556:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
 1557:     return () if (! defined($sname) || ! defined($sdom));
 1558:     #
 1559:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1560:     #
 1561:     my $cachefilename = $Apache::lonnet::tmpdir.$ENV{'user.name'}.'_'.
 1562:                                                 $ENV{'user.domain'}.'_'.
 1563:                                                 $courseid.'_student_data.db';
 1564:     my %cache;
 1565:     #
 1566:     my %student_data; # return values go here
 1567:     #
 1568:     my $updatetime = 0;
 1569:     my $key = &Apache::lonnet::escape($sname).':'.
 1570:               &Apache::lonnet::escape($sdom).':';
 1571:     # Open the cache file
 1572:     if (tie(%cache,'GDBM_File',$cachefilename,&GDBM_READER(),0640)) {
 1573:         if (exists($cache{$key.'time'})) {
 1574:             $updatetime = $cache{$key.'time'};
 1575: #            &Apache::lonnet::logthis('got updatetime of '.$updatetime);
 1576:         }
 1577:         untie(%cache);
 1578:     }
 1579:     # timestamp/devalidation 
 1580:     my $modifiedtime = 1;
 1581:     # Take whatever steps are neccessary at this point to give $modifiedtime a
 1582:     # new value
 1583:     #
 1584:     if (($updatetime < $modifiedtime) || 
 1585:         (defined($forcedownload) && $forcedownload)) {
 1586: #        &Apache::lonnet::logthis("loading data");
 1587:         # Get all the students current data
 1588:         my $time_of_retrieval = time;
 1589:         my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
 1590:         if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
 1591:             &Apache::lonnet::logthis('error getting data for '.
 1592:                                      $sname.':'.$sdom.' in course '.$courseid.
 1593:                                      ':'.$tmp[0]);
 1594:             return ();
 1595:         }
 1596:         %student_data = @tmp;
 1597:         #
 1598:         # Store away the data
 1599:         #
 1600:         # The cache structure is colon deliminated.  
 1601:         # $uname:$udom:time  => timestamp
 1602:         # $uname:$udom:$symb => $parm1:$val1:$parm2:$val2 ...
 1603:         #
 1604:         # BEWARE: The colons are NOT escaped so can search with escaped 
 1605:         #         keys instead of unescaping every key.
 1606:         #
 1607:         if (tie(%cache,'GDBM_File',$cachefilename,&GDBM_WRCREAT(),0640)) {
 1608: #            &Apache::lonnet::logthis("writing data");
 1609:             while (my ($current_symb,$param_hash) = each(%student_data)) {
 1610:                 my @Parameters = %{$param_hash};
 1611:                 my $value = join(':',map { &Apache::lonnet::escape($_); } 
 1612:                                  @Parameters);
 1613:                 # Store away the values
 1614:                 $cache{$key.&Apache::lonnet::escape($current_symb)}=$value;
 1615:             }
 1616:             $cache{$key.'time'}=$time_of_retrieval;
 1617:             untie(%cache);
 1618:         }
 1619:     } else {
 1620:         &Apache::lonnet::logthis('retrieving cached data ');
 1621:         if (tie(%cache,'GDBM_File',$cachefilename,&GDBM_READER(),0640)) {
 1622:             if (defined($symb)) {
 1623:                 my  $searchkey = $key.&Apache::lonnet::escape($symb);
 1624:                 if (exists($cache{$searchkey})) {
 1625:                     $student_data{$symb} = &make_into_hash($cache{$searchkey});
 1626:                 }
 1627:             } else {
 1628:                 my $searchkey = '^'.$key.'(.*)$';#'
 1629:                 while (my ($testkey,$params)=each(%cache)) {
 1630:                     if ($testkey =~ /$searchkey/) { # \Q \E?  May be necc.
 1631:                         my $tmpsymb = $1;
 1632:                         next if ($tmpsymb =~ 'time');
 1633: #                        &Apache::lonnet::logthis('found '.$tmpsymb.':');
 1634:                         $student_data{&Apache::lonnet::unescape($tmpsymb)} = 
 1635:                             &make_into_hash($params);
 1636:                     }
 1637:                 }
 1638:             }
 1639:             untie(%cache);
 1640:         }
 1641:     }
 1642:     if (! defined($symb)) {
 1643: #        &Apache::lonnet::logthis("returning all data");
 1644:         return %student_data;
 1645:     } elsif (exists($student_data{$symb})) {
 1646: #        &Apache::lonnet::logthis("returning data for symb=".$symb);
 1647:         return %{$student_data{$symb}};
 1648:     } else {
 1649:         return ();
 1650:     }
 1651: }
 1652: 
 1653: ################################################
 1654: ################################################
 1655: 
 1656: =pod
 1657: 
 1658: =item &get_classlist();
 1659: 
 1660: Retrieve the classist of a given class or of the current class.  Student
 1661: information is returned from the classlist.db file and, if needed,
 1662: from the students environment.
 1663: 
 1664: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
 1665: and course number, respectively).  Any omitted arguments will be taken 
 1666: from the current environment ($ENV{'request.course.id'},
 1667: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
 1668: 
 1669: Returns a reference to a hash which contains:
 1670:  keys    '$sname:$sdom'
 1671:  values  [$end,$start,$id,$section,$fullname]
 1672: 
 1673: =cut
 1674: 
 1675: ################################################
 1676: ################################################
 1677: 
 1678: sub get_classlist {
 1679:     my ($cid,$cdom,$cnum) = @_;
 1680:     $cid = $cid || $ENV{'request.course.id'};
 1681:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
 1682:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
 1683:    my $now = time;
 1684:     #
 1685:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
 1686:     while (my ($student,$info) = each(%classlist)) {
 1687:         return undef if ($student =~ /^(con_lost|error|no_such_host)/i);
 1688:         my ($sname,$sdom) = split(/:/,$student);
 1689:         my @Values = split(/:/,$info);
 1690:         my ($end,$start,$id,$section,$fullname);
 1691:         if (@Values > 2) {
 1692:             ($end,$start,$id,$section,$fullname) = @Values;
 1693:         } else { # We have to get the data ourselves
 1694:             ($end,$start) = @Values;
 1695:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
 1696:             my %info=&Apache::lonnet::get('environment',
 1697:                                           ['firstname','middlename',
 1698:                                            'lastname','generation','id'],
 1699:                                           $sdom, $sname);
 1700:             my ($tmp) = keys(%info);
 1701:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 1702:                 $fullname = 'not available';
 1703:                 $id = 'not available';
 1704:                 &Apache::lonnet::logthis('unable to retrieve environment '.
 1705:                                          'for '.$sname.':'.$sdom);
 1706:             } else {
 1707:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
 1708:                                                        firstname middlename/});
 1709:                 $id = $info{'id'};
 1710:             }
 1711:             # Update the classlist with this students information
 1712:             if ($fullname ne 'not available') {
 1713:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
 1714:                 my $reply=&Apache::lonnet::cput('classlist',
 1715:                                                 {$student => $enrolldata},
 1716:                                                 $cdom,$cnum);
 1717:                 if ($reply !~ /^(ok|delayed)/) {
 1718:                     &Apache::lonnet::logthis('Unable to update classlist for '.
 1719:                                              'student '.$sname.':'.$sdom.
 1720:                                              ' error:'.$reply);
 1721:                 }
 1722:             }
 1723:         }
 1724:         my $status='Expired';
 1725:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
 1726:             $status='Active';
 1727:         }
 1728:         $classlist{$student} = 
 1729:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
 1730:     }
 1731:     if (wantarray()) {
 1732:         return (\%classlist,['domain','username','end','start','id',
 1733:                              'section','fullname','status']);
 1734:     } else {
 1735:         return \%classlist;
 1736:     }
 1737: }
 1738: 
 1739: # ----- END HELPER FUNCTIONS --------------------------------------------
 1740: 
 1741: 1;
 1742: __END__
 1743: 
 1744: 

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