File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.52: download - view: text, annotated - select for diffs
Tue Feb 25 20:36:29 2003 UTC (21 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
&get_sequence_assessment_data() handles top level map better:
   title is set to course description
   symb is set to 'top'
   src is set (which is new) to 'not applicable' (which is stupid)

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

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