File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.45: download - view: text, annotated - select for diffs
Thu Feb 13 14:49:16 2003 UTC (21 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added &get_sequence_assessment_data(), which is entirely experimental and
should not be used at this time.

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

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