File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.49: download - view: text, annotated - select for diffs
Thu Feb 20 14:28:25 2003 UTC (21 years, 5 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
&get_sequence_assessment_data() now additionally returns array refs holding
the sequences and assessments which appear in the course.

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

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