File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.88: download - view: text, annotated - select for diffs
Wed Sep 24 18:01:01 2003 UTC (20 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Update to get_sequence_assessment_data to expect arrays from responseType
and responseIds.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: loncoursedata.pm,v 1.88 2003/09/24 18:01:01 matthew Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: ###
   28: 
   29: =pod
   30: 
   31: =head1 NAME
   32: 
   33: loncoursedata
   34: 
   35: =head1 SYNOPSIS
   36: 
   37: Set of functions that download and process student and course information.
   38: 
   39: =head1 PACKAGES USED
   40: 
   41:  Apache::Constants qw(:common :http)
   42:  Apache::lonnet()
   43:  Apache::lonhtmlcommon
   44:  HTML::TokeParser
   45:  GDBM_File
   46: 
   47: =cut
   48: 
   49: package Apache::loncoursedata;
   50: 
   51: use strict;
   52: use Apache::Constants qw(:common :http);
   53: use Apache::lonnet();
   54: use Apache::lonhtmlcommon;
   55: use Time::HiRes;
   56: use Apache::lonmysql;
   57: use HTML::TokeParser;
   58: use GDBM_File;
   59: 
   60: =pod
   61: 
   62: =head1 DOWNLOAD INFORMATION
   63: 
   64: This section contains all the functions that get data from other servers 
   65: and/or itself.
   66: 
   67: =cut
   68: 
   69: ####################################################
   70: ####################################################
   71: 
   72: =pod
   73: 
   74: =item &get_sequence_assessment_data()
   75: 
   76: AT THIS TIME THE USE OF THIS FUNCTION IS *NOT* RECOMMENDED
   77: 
   78: Use lonnavmaps to build a data structure describing the order and 
   79: assessment contents of each sequence in the current course.
   80: 
   81: The returned structure is a hash reference. 
   82: 
   83: { title => 'title',
   84:   symb  => 'symb',
   85:   src   => '/s/o/u/r/c/e',
   86:   type  => (container|assessment),
   87:   num_assess   => 2,               # only for container
   88:   parts        => [11,13,15],      # only for assessment
   89:   response_ids => [12,14,16],      # only for assessment
   90:   contents     => [........]       # only for container
   91: }
   92: 
   93: $hash->{'contents'} is a reference to an array of hashes of the same structure.
   94: 
   95: Also returned are array references to the sequences and assessments contained
   96: in the course.
   97: 
   98: 
   99: =cut
  100: 
  101: ####################################################
  102: ####################################################
  103: sub get_sequence_assessment_data {
  104:     my $fn=$ENV{'request.course.fn'};
  105:     ##
  106:     ## use navmaps
  107:     my $navmap = Apache::lonnavmaps::navmap->new();
  108:     if (!defined($navmap)) {
  109:         return 'Can not open Coursemap';
  110:     }
  111:     # We explicity grab the top level map because I am not sure we
  112:     # are pulling it from the iterator.
  113:     my $top_level_map = $navmap->getById('0.0');
  114:     #
  115:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  116:     my $curRes = $iterator->next(); # Top level sequence
  117:     ##
  118:     ## Prime the pump 
  119:     ## 
  120:     ## We are going to loop until we run out of sequences/pages to explore for
  121:     ## resources.  This means we have to start out with something to look
  122:     ## at.
  123:     my $title = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  124:     my $symb  = $top_level_map->symb();
  125:     my $src   = $top_level_map->src();
  126:     my $randompick = $top_level_map->randompick();
  127:     #
  128:     my @Sequences; 
  129:     my @Assessments;
  130:     my @Nested_Sequences = ();   # Stack of sequences, keeps track of depth
  131:     my $top = { title    => $title,
  132:                 src      => $src,
  133:                 symb     => $symb,
  134:                 type     => 'container',
  135:                 num_assess => 0,
  136:                 num_assess_parts => 0,
  137:                 contents   => [], 
  138:                 randompick => $randompick,
  139:             };
  140:     push (@Sequences,$top);
  141:     push (@Nested_Sequences, $top);
  142:     #
  143:     # We need to keep track of which sequences contain homework problems
  144:     # 
  145:     my $previous_too;
  146:     my $previous;
  147:     while (scalar(@Nested_Sequences)) {
  148:         $previous_too = $previous;
  149:         $previous = $curRes;
  150:         $curRes = $iterator->next();
  151:         my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
  152:         if ($curRes == $iterator->BEGIN_MAP()) {
  153:             if (! ref($previous)) {
  154:                 $previous = $previous_too;
  155:             }
  156:             if (! ref($previous)) {
  157:                 next;
  158:             }
  159:             # get the map itself, instead of BEGIN_MAP
  160:             $title = $previous->title();
  161:             $title =~ s/\:/\&\#058;/g;
  162:             $symb  = $previous->symb();
  163:             $src   = $previous->src();
  164:             # pick up the filename if there is no title available
  165:             if (! defined($title) || $title eq '') {
  166:                 ($title) = ($src=~/\/([^\/]*)$/);
  167:             }
  168:             $randompick = $previous->randompick();
  169:             my $newmap = { title    => $title,
  170:                            src      => $src,
  171:                            symb     => $symb,
  172:                            type     => 'container',
  173:                            num_assess => 0,
  174:                            randompick => $randompick,
  175:                            contents   => [],
  176:                        };
  177:             push (@{$currentmap->{'contents'}},$newmap); # this is permanent
  178:             push (@Sequences,$newmap);
  179:             push (@Nested_Sequences, $newmap); # this is a stack
  180:             next;
  181:         }
  182:         if ($curRes == $iterator->END_MAP()) {
  183:             pop(@Nested_Sequences);
  184:             next;
  185:         }
  186:         next if (! ref($curRes));
  187:         next if (! $curRes->is_problem());# && !$curRes->randomout);
  188:         # Okay, from here on out we only deal with assessments
  189:         $title = $curRes->title();
  190:         $title =~ s/\:/\&\#058;/g;
  191:         $symb  = $curRes->symb();
  192:         $src   = $curRes->src();
  193:         my $parts = $curRes->parts();
  194:         my %partdata;
  195:         foreach my $part (@$parts) {
  196:             my @Responses = $curRes->responseType($part);
  197:             my @Ids       = $curRes->responseIds($part);
  198:             $partdata{$part}->{'ResponseTypes'}= \@Responses;
  199:             $partdata{$part}->{'ResponseIds'}  = \@Ids;
  200:         }
  201:         my $assessment = { title => $title,
  202:                            src   => $src,
  203:                            symb  => $symb,
  204:                            type  => 'assessment',
  205:                            parts => $parts,
  206:                            num_parts => scalar(@$parts),
  207:                            partdata => \%partdata,
  208:                        };
  209:         push(@Assessments,$assessment);
  210:         push(@{$currentmap->{'contents'}},$assessment);
  211:         $currentmap->{'num_assess'}++;
  212:         $currentmap->{'num_assess_parts'}+= scalar(@$parts);
  213:     }
  214:     $navmap->untieHashes();
  215:     return ($top,\@Sequences,\@Assessments);
  216: }
  217: 
  218: sub LoadDiscussion {
  219:     my ($courseID)=@_;
  220:     my %Discuss=();
  221:     my %contrib=&Apache::lonnet::dump(
  222:                 $courseID,
  223:                 $ENV{'course.'.$courseID.'.domain'},
  224:                 $ENV{'course.'.$courseID.'.num'});
  225: 				 
  226:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
  227: 
  228:     foreach my $temp(keys %contrib) {
  229: 	if ($temp=~/^version/) {
  230: 	    my $ver=$contrib{$temp};
  231: 	    my ($dummy,$prb)=split(':',$temp);
  232: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
  233: 		my $name=$contrib{"$idx:$prb:sendername"};
  234: 		$Discuss{"$name:$prb"}=$idx;	
  235: 	    }
  236: 	}
  237:     }       
  238: 
  239:     return \%Discuss;
  240: }
  241: 
  242: ################################################
  243: ################################################
  244: 
  245: =pod
  246: 
  247: =item &GetUserName(username,userdomain)
  248: 
  249: Returns a hash with the following entries:
  250:    'firstname', 'middlename', 'lastname', 'generation', and 'fullname'
  251: 
  252:    'fullname' is the result of &Apache::loncoursedata::ProcessFullName.
  253: 
  254: =cut
  255: 
  256: ################################################
  257: ################################################
  258: sub GetUserName {
  259:     my ($username,$userdomain) = @_;
  260:     $username = $ENV{'user.name'} if (! defined($username));
  261:     $userdomain = $ENV{'user.domain'} if (! defined($username));
  262:     my %userenv = &Apache::lonnet::get('environment',
  263:                            ['firstname','middlename','lastname','generation'],
  264:                                        $userdomain,$username);
  265:     $userenv{'fullname'} = &ProcessFullName($userenv{'lastname'},
  266:                                             $userenv{'generation'},
  267:                                             $userenv{'firstname'},
  268:                                             $userenv{'middlename'});
  269:     return %userenv;
  270: }
  271: 
  272: ################################################
  273: ################################################
  274: 
  275: =pod
  276: 
  277: =item &ProcessFullName()
  278: 
  279: Takes lastname, generation, firstname, and middlename (or some partial
  280: set of this data) and returns the full name version as a string.  Format
  281: is Lastname generation, firstname middlename or a subset of this.
  282: 
  283: =cut
  284: 
  285: ################################################
  286: ################################################
  287: sub ProcessFullName {
  288:     my ($lastname, $generation, $firstname, $middlename)=@_;
  289:     my $Str = '';
  290: 
  291:     # Strip whitespace preceeding & following name components.
  292:     $lastname   =~ s/(\s+$|^\s+)//g;
  293:     $generation =~ s/(\s+$|^\s+)//g;
  294:     $firstname  =~ s/(\s+$|^\s+)//g;
  295:     $middlename =~ s/(\s+$|^\s+)//g;
  296: 
  297:     if($lastname ne '') {
  298: 	$Str .= $lastname;
  299: 	$Str .= ' '.$generation if ($generation ne '');
  300: 	$Str .= ',';
  301:         $Str .= ' '.$firstname  if ($firstname ne '');
  302:         $Str .= ' '.$middlename if ($middlename ne '');
  303:     } else {
  304:         $Str .= $firstname      if ($firstname ne '');
  305:         $Str .= ' '.$middlename if ($middlename ne '');
  306:         $Str .= ' '.$generation if ($generation ne '');
  307:     }
  308: 
  309:     return $Str;
  310: }
  311: 
  312: ################################################
  313: ################################################
  314: 
  315: =pod
  316: 
  317: =item &make_into_hash($values);
  318: 
  319: Returns a reference to a hash as described by $values.  $values is
  320: assumed to be the result of 
  321:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
  322: 
  323: This is a helper function for get_current_state.
  324: 
  325: =cut
  326: 
  327: ################################################
  328: ################################################
  329: sub make_into_hash {
  330:     my $values = shift;
  331:     my %tmp = map { &Apache::lonnet::unescape($_); }
  332:                                            split(':',$values);
  333:     return \%tmp;
  334: }
  335: 
  336: 
  337: ################################################
  338: ################################################
  339: 
  340: =pod
  341: 
  342: =head1 LOCAL DATA CACHING SUBROUTINES
  343: 
  344: The local caching is done using MySQL.  There is no fall-back implementation
  345: if MySQL is not running.
  346: 
  347: The programmers interface is to call &get_current_state() or some other
  348: primary interface subroutine (described below).  The internals of this 
  349: storage system are documented here.
  350: 
  351: There are six tables used to store student performance data (the results of
  352: a dumpcurrent).  Each of these tables is created in MySQL with a name of
  353: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
  354: for the table.  The tables and their purposes are described below.
  355: 
  356: Some notes before we get started.
  357: 
  358: Each table must have a PRIMARY KEY, which is a column or set of columns which
  359: will serve to uniquely identify a row of data.  NULL is not allowed!
  360: 
  361: INDEXes work best on integer data.
  362: 
  363: JOIN is used to combine data from many tables into one output.
  364: 
  365: lonmysql.pm is used for some of the interface, specifically the table creation
  366: calls.  The inserts are done in bulk by directly calling the database handler.
  367: The SELECT ... JOIN statement used to retrieve the data does not have an
  368: interface in lonmysql.pm and I shudder at the thought of writing one.
  369: 
  370: =head3 Table Descriptions
  371: 
  372: =over 4
  373: 
  374: =item $symb_table
  375: 
  376: The symb_table has two columns.  The first is a 'symb_id' and the second
  377: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
  378: automatically by MySQL so inserts should be done on this table with an
  379: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
  380: 
  381: =item $part_table
  382: 
  383: The part_table has two columns.  The first is a 'part_id' and the second
  384: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
  385: generated automatically by MySQL so inserts should be done on this table with
  386: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
  387: characters) and a KEY on 'part_id'.
  388: 
  389: =item $student_table
  390: 
  391: The student_table has two columns.  The first is a 'student_id' and the second
  392: is the text description of the 'student' (typically username:domain) (less
  393: than 100 characters).  The 'student_id' is automatically generated by MySQL.
  394: The use of the name 'student_id' is loaded, I know, but this ID is used ONLY 
  395: internally to the MySQL database and is not the same as the students ID 
  396: (stored in the students environment).  This table has its PRIMARY KEY on the
  397: 'student' (100 characters).
  398: 
  399: =item $studentdata_table
  400: 
  401: The studentdata_table has four columns.  The first is 'student_id', the unique
  402: id of the student.  The second is the time the students data was last updated.
  403: The third is the students section.  The fourth is the students current
  404: classification.  This table has its PRIMARY KEY on 'student_id'.
  405: 
  406: =item $performance_table
  407: 
  408: The performance_table has 9 columns.  The first three are 'symb_id', 
  409: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
  410: and are directly related to the $symb_table, $student_table, and $part_table
  411: described above.  MySQL does better indexing on numeric items than text,
  412: so we use these three "index tables".  The remaining columns are
  413: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
  414: These are either the MySQL type TINYTEXT or various integers ('tries' and 
  415: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
  416: For use of this table, see the functions described below.
  417: 
  418: =item $parameters_table
  419: 
  420: The parameters_table holds the data that does not fit neatly into the
  421: performance_table.  The parameters table has four columns: 'symb_id',
  422: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
  423: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
  424: limited to 255 characters.  'value' is limited to 64k characters.
  425: 
  426: =back
  427: 
  428: =head3 Important Subroutines
  429: 
  430: Here is a brief overview of the subroutines which are likely to be of 
  431: interest:
  432: 
  433: =over 4
  434: 
  435: =item &get_current_state(): programmers interface.
  436: 
  437: =item &init_dbs(): table creation
  438: 
  439: =item &update_student_data(): data storage calls
  440: 
  441: =item &get_student_data_from_performance_cache(): data retrieval
  442: 
  443: =back
  444: 
  445: =head3 Main Documentation
  446: 
  447: =over 4
  448: 
  449: =cut
  450: 
  451: ################################################
  452: ################################################
  453: 
  454: ################################################
  455: ################################################
  456: {
  457: 
  458: my $current_course ='';
  459: my $symb_table;
  460: my $part_table;
  461: my $student_table;
  462: my $studentdata_table;
  463: my $performance_table;
  464: my $parameters_table;
  465: 
  466: ################################################
  467: ################################################
  468: 
  469: =pod
  470: 
  471: =item &init_dbs()
  472: 
  473: Input: course id
  474: 
  475: Output: 0 on success, positive integer on error
  476: 
  477: This routine issues the calls to lonmysql to create the tables used to
  478: store student data.
  479: 
  480: =cut
  481: 
  482: ################################################
  483: ################################################
  484: sub init_dbs {
  485:     my $courseid = shift;
  486:     &setup_table_names($courseid);
  487:     #
  488:     # Drop any of the existing tables
  489:     foreach my $table ($symb_table,$part_table,$student_table,
  490:                        $studentdata_table,$performance_table,
  491:                        $parameters_table) {
  492:         &Apache::lonmysql::drop_table($table);
  493:     }
  494:     #
  495:     # Note - changes to this table must be reflected in the code that 
  496:     # stores the data (calls &Apache::lonmysql::store_row with this table
  497:     # id
  498:     my $symb_table_def = {
  499:         id => $symb_table,
  500:         permanent => 'no',
  501:         columns => [{ name => 'symb_id',
  502:                       type => 'MEDIUMINT UNSIGNED',
  503:                       restrictions => 'NOT NULL',
  504:                       auto_inc     => 'yes', },
  505:                     { name => 'symb',
  506:                       type => 'MEDIUMTEXT',
  507:                       restrictions => 'NOT NULL'},
  508:                     ],
  509:         'PRIMARY KEY' => ['symb_id'],
  510:     };
  511:     #
  512:     my $part_table_def = {
  513:         id => $part_table,
  514:         permanent => 'no',
  515:         columns => [{ name => 'part_id',
  516:                       type => 'MEDIUMINT UNSIGNED',
  517:                       restrictions => 'NOT NULL',
  518:                       auto_inc     => 'yes', },
  519:                     { name => 'part',
  520:                       type => 'VARCHAR(100)',
  521:                       restrictions => 'NOT NULL'},
  522:                     ],
  523:         'PRIMARY KEY' => ['part (100)'],
  524:         'KEY' => [{ columns => ['part_id']},],
  525:     };
  526:     #
  527:     my $student_table_def = {
  528:         id => $student_table,
  529:         permanent => 'no',
  530:         columns => [{ name => 'student_id',
  531:                       type => 'MEDIUMINT UNSIGNED',
  532:                       restrictions => 'NOT NULL',
  533:                       auto_inc     => 'yes', },
  534:                     { name => 'student',
  535:                       type => 'VARCHAR(100)',
  536:                       restrictions => 'NOT NULL'},
  537:                     { name => 'classification',
  538:                       type => 'varchar(100)', },
  539:                     ],
  540:         'PRIMARY KEY' => ['student (100)'],
  541:         'KEY' => [{ columns => ['student_id']},],
  542:     };
  543:     #
  544:     my $studentdata_table_def = {
  545:         id => $studentdata_table,
  546:         permanent => 'no',
  547:         columns => [{ name => 'student_id',
  548:                       type => 'MEDIUMINT UNSIGNED',
  549:                       restrictions => 'NOT NULL UNIQUE',},
  550:                     { name => 'updatetime',
  551:                       type => 'INT UNSIGNED',
  552:                       restrictions => 'NOT NULL' },
  553:                     { name => 'section',
  554:                       type => 'VARCHAR(100)'},
  555:                     { name => 'classification',
  556:                       type => 'VARCHAR(100)', },
  557:                     ],
  558:         'PRIMARY KEY' => ['student_id'],
  559:     };
  560:     #
  561:     my $performance_table_def = {
  562:         id => $performance_table,
  563:         permanent => 'no',
  564:         columns => [{ name => 'symb_id',
  565:                       type => 'MEDIUMINT UNSIGNED',
  566:                       restrictions => 'NOT NULL'  },
  567:                     { name => 'student_id',
  568:                       type => 'MEDIUMINT UNSIGNED',
  569:                       restrictions => 'NOT NULL'  },
  570:                     { name => 'part_id',
  571:                       type => 'MEDIUMINT UNSIGNED',
  572:                       restrictions => 'NOT NULL' },
  573:                     { name => 'part',
  574:                       type => 'VARCHAR(100)',
  575:                       restrictions => 'NOT NULL'},                    
  576:                     { name => 'solved',
  577:                       type => 'TINYTEXT' },
  578:                     { name => 'tries',
  579:                       type => 'SMALLINT UNSIGNED' },
  580:                     { name => 'awarded',
  581:                       type => 'TINYTEXT' },
  582:                     { name => 'award',
  583:                       type => 'TINYTEXT' },
  584:                     { name => 'awarddetail',
  585:                       type => 'TINYTEXT' },
  586:                     { name => 'timestamp',
  587:                       type => 'INT UNSIGNED'},
  588:                     ],
  589:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
  590:         'KEY' => [{ columns=>['student_id'] },
  591:                   { columns=>['symb_id'] },],
  592:     };
  593:     #
  594:     my $parameters_table_def = {
  595:         id => $parameters_table,
  596:         permanent => 'no',
  597:         columns => [{ name => 'symb_id',
  598:                       type => 'MEDIUMINT UNSIGNED',
  599:                       restrictions => 'NOT NULL'  },
  600:                     { name => 'student_id',
  601:                       type => 'MEDIUMINT UNSIGNED',
  602:                       restrictions => 'NOT NULL'  },
  603:                     { name => 'parameter',
  604:                       type => 'TINYTEXT',
  605:                       restrictions => 'NOT NULL'  },
  606:                     { name => 'value',
  607:                       type => 'MEDIUMTEXT' },
  608:                     ],
  609:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
  610:     };
  611:     #
  612:     # Create the tables
  613:     my $tableid;
  614:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
  615:     if (! defined($tableid)) {
  616:         &Apache::lonnet::logthis("error creating symb_table: ".
  617:                                  &Apache::lonmysql::get_error());
  618:         return 1;
  619:     }
  620:     #
  621:     $tableid = &Apache::lonmysql::create_table($part_table_def);
  622:     if (! defined($tableid)) {
  623:         &Apache::lonnet::logthis("error creating part_table: ".
  624:                                  &Apache::lonmysql::get_error());
  625:         return 2;
  626:     }
  627:     #
  628:     $tableid = &Apache::lonmysql::create_table($student_table_def);
  629:     if (! defined($tableid)) {
  630:         &Apache::lonnet::logthis("error creating student_table: ".
  631:                                  &Apache::lonmysql::get_error());
  632:         return 3;
  633:     }
  634:     #
  635:     $tableid = &Apache::lonmysql::create_table($studentdata_table_def);
  636:     if (! defined($tableid)) {
  637:         &Apache::lonnet::logthis("error creating studentdata_table: ".
  638:                                  &Apache::lonmysql::get_error());
  639:         return 4;
  640:     }
  641:     #
  642:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
  643:     if (! defined($tableid)) {
  644:         &Apache::lonnet::logthis("error creating preformance_table: ".
  645:                                  &Apache::lonmysql::get_error());
  646:         return 5;
  647:     }
  648:     #
  649:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
  650:     if (! defined($tableid)) {
  651:         &Apache::lonnet::logthis("error creating parameters_table: ".
  652:                                  &Apache::lonmysql::get_error());
  653:         return 6;
  654:     }
  655:     return 0;
  656: }
  657: 
  658: ################################################
  659: ################################################
  660: 
  661: =pod
  662: 
  663: =item &delete_caches()
  664: 
  665: =cut
  666: 
  667: ################################################
  668: ################################################
  669: sub delete_caches {
  670:     my $courseid = shift;
  671:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
  672:     #
  673:     &setup_table_names($courseid);
  674:     #
  675:     my $dbh = &Apache::lonmysql::get_dbh();
  676:     foreach my $table ($symb_table,$part_table,$student_table,
  677:                        $studentdata_table,$performance_table,
  678:                        $parameters_table ){
  679:         my $command = 'DROP TABLE '.$table.';';
  680:         $dbh->do($command);
  681:         if ($dbh->err) {
  682:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
  683:         }
  684:     }
  685:     return;
  686: }
  687: 
  688: ################################################
  689: ################################################
  690: 
  691: =pod
  692: 
  693: =item &get_part_id()
  694: 
  695: Get the MySQL id of a problem part string.
  696: 
  697: Input: $part
  698: 
  699: Output: undef on error, integer $part_id on success.
  700: 
  701: =item &get_part()
  702: 
  703: Get the string describing a part from the MySQL id of the problem part.
  704: 
  705: Input: $part_id
  706: 
  707: Output: undef on error, $part string on success.
  708: 
  709: =cut
  710: 
  711: ################################################
  712: ################################################
  713: 
  714: my $have_read_part_table = 0;
  715: my %ids_by_part;
  716: my %parts_by_id;
  717: 
  718: sub get_part_id {
  719:     my ($part) = @_;
  720:     $part = 0 if (! defined($part));
  721:     if (! $have_read_part_table) {
  722:         my @Result = &Apache::lonmysql::get_rows($part_table);
  723:         foreach (@Result) {
  724:             $ids_by_part{$_->[1]}=$_->[0];
  725:         }
  726:         $have_read_part_table = 1;
  727:     }
  728:     if (! exists($ids_by_part{$part})) {
  729:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
  730:         undef(%ids_by_part);
  731:         my @Result = &Apache::lonmysql::get_rows($part_table);
  732:         foreach (@Result) {
  733:             $ids_by_part{$_->[1]}=$_->[0];
  734:         }
  735:     }
  736:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
  737:     return undef; # error
  738: }
  739: 
  740: sub get_part {
  741:     my ($part_id) = @_;
  742:     if (! exists($parts_by_id{$part_id})  || 
  743:         ! defined($parts_by_id{$part_id}) ||
  744:         $parts_by_id{$part_id} eq '') {
  745:         my @Result = &Apache::lonmysql::get_rows($part_table);
  746:         foreach (@Result) {
  747:             $parts_by_id{$_->[0]}=$_->[1];
  748:         }
  749:     }
  750:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
  751:     return undef; # error
  752: }
  753: 
  754: ################################################
  755: ################################################
  756: 
  757: =pod
  758: 
  759: =item &get_symb_id()
  760: 
  761: Get the MySQL id of a symb.
  762: 
  763: Input: $symb
  764: 
  765: Output: undef on error, integer $symb_id on success.
  766: 
  767: =item &get_symb()
  768: 
  769: Get the symb associated with a MySQL symb_id.
  770: 
  771: Input: $symb_id
  772: 
  773: Output: undef on error, $symb on success.
  774: 
  775: =cut
  776: 
  777: ################################################
  778: ################################################
  779: 
  780: my $have_read_symb_table = 0;
  781: my %ids_by_symb;
  782: my %symbs_by_id;
  783: 
  784: sub get_symb_id {
  785:     my ($symb) = @_;
  786:     if (! $have_read_symb_table) {
  787:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  788:         foreach (@Result) {
  789:             $ids_by_symb{$_->[1]}=$_->[0];
  790:         }
  791:         $have_read_symb_table = 1;
  792:     }
  793:     if (! exists($ids_by_symb{$symb})) {
  794:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
  795:         undef(%ids_by_symb);
  796:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  797:         foreach (@Result) {
  798:             $ids_by_symb{$_->[1]}=$_->[0];
  799:         }
  800:     }
  801:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
  802:     return undef; # error
  803: }
  804: 
  805: sub get_symb {
  806:     my ($symb_id) = @_;
  807:     if (! exists($symbs_by_id{$symb_id})  || 
  808:         ! defined($symbs_by_id{$symb_id}) ||
  809:         $symbs_by_id{$symb_id} eq '') {
  810:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  811:         foreach (@Result) {
  812:             $symbs_by_id{$_->[0]}=$_->[1];
  813:         }
  814:     }
  815:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
  816:     return undef; # error
  817: }
  818: 
  819: ################################################
  820: ################################################
  821: 
  822: =pod
  823: 
  824: =item &get_student_id()
  825: 
  826: Get the MySQL id of a student.
  827: 
  828: Input: $sname, $dom
  829: 
  830: Output: undef on error, integer $student_id on success.
  831: 
  832: =item &get_student()
  833: 
  834: Get student username:domain associated with the MySQL student_id.
  835: 
  836: Input: $student_id
  837: 
  838: Output: undef on error, string $student (username:domain) on success.
  839: 
  840: =cut
  841: 
  842: ################################################
  843: ################################################
  844: 
  845: my $have_read_student_table = 0;
  846: my %ids_by_student;
  847: my %students_by_id;
  848: 
  849: sub get_student_id {
  850:     my ($sname,$sdom) = @_;
  851:     my $student = $sname.':'.$sdom;
  852:     if (! $have_read_student_table) {
  853:         my @Result = &Apache::lonmysql::get_rows($student_table);
  854:         foreach (@Result) {
  855:             $ids_by_student{$_->[1]}=$_->[0];
  856:         }
  857:         $have_read_student_table = 1;
  858:     }
  859:     if (! exists($ids_by_student{$student})) {
  860:         &Apache::lonmysql::store_row($student_table,[undef,$student,undef]);
  861:         undef(%ids_by_student);
  862:         my @Result = &Apache::lonmysql::get_rows($student_table);
  863:         foreach (@Result) {
  864:             $ids_by_student{$_->[1]}=$_->[0];
  865:         }
  866:     }
  867:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
  868:     return undef; # error
  869: }
  870: 
  871: sub get_student {
  872:     my ($student_id) = @_;
  873:     if (! exists($students_by_id{$student_id})  || 
  874:         ! defined($students_by_id{$student_id}) ||
  875:         $students_by_id{$student_id} eq '') {
  876:         my @Result = &Apache::lonmysql::get_rows($student_table);
  877:         foreach (@Result) {
  878:             $students_by_id{$_->[0]}=$_->[1];
  879:         }
  880:     }
  881:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
  882:     return undef; # error
  883: }
  884: 
  885: ################################################
  886: ################################################
  887: 
  888: =pod
  889: 
  890: =item &update_student_data()
  891: 
  892: Input: $sname, $sdom, $courseid
  893: 
  894: Output: $returnstatus, \%student_data
  895: 
  896: $returnstatus is a string describing any errors that occured.  'okay' is the
  897: default.
  898: \%student_data is the data returned by a call to lonnet::currentdump.
  899: 
  900: This subroutine loads a students data using lonnet::currentdump and inserts
  901: it into the MySQL database.  The inserts are done on two tables, 
  902: $performance_table and $parameters_table.  $parameters_table holds the data 
  903: that is not included in $performance_table.  See the description of 
  904: $performance_table elsewhere in this file.  The INSERT calls are made
  905: directly by this subroutine, not through lonmysql because we do a 'bulk'
  906: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
  907: insert multiple rows at a time.  If anything has gone wrong during this
  908: process, $returnstatus is updated with a description of the error and
  909: \%student_data is returned.  
  910: 
  911: Notice we do not insert the data and immediately query it.  This means it
  912: is possible for there to be data returned this first time that is not 
  913: available the second time.  CYA.
  914: 
  915: =cut
  916: 
  917: ################################################
  918: ################################################
  919: sub update_student_data {
  920:     my ($sname,$sdom,$courseid) = @_;
  921:     #
  922:     # Set up database names
  923:     &setup_table_names($courseid);
  924:     #
  925:     my $student_id = &get_student_id($sname,$sdom);
  926:     my $student = $sname.':'.$sdom;
  927:     #
  928:     my $returnstatus = 'okay';
  929:     #
  930:     # Download students data
  931:     my $time_of_retrieval = time;
  932:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
  933:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
  934:         &Apache::lonnet::logthis('error getting data for '.
  935:                                  $sname.':'.$sdom.' in course '.$courseid.
  936:                                  ':'.$tmp[0]);
  937:         $returnstatus = 'error getting data';
  938:         return ($returnstatus,undef);
  939:     }
  940:     if (scalar(@tmp) < 1) {
  941:         return ('no data',undef);
  942:     }
  943:     my %student_data = @tmp;
  944:     #
  945:     # Remove all of the students data from the table
  946:     my $dbh = &Apache::lonmysql::get_dbh();
  947:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
  948:              $student_id);
  949:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
  950:              $student_id);
  951:     #
  952:     # Store away the data
  953:     #
  954:     my $starttime = Time::HiRes::time;
  955:     my $elapsed = 0;
  956:     my $rows_stored;
  957:     my $store_parameters_command  = 'INSERT INTO '.$parameters_table.
  958:         ' VALUES '."\n";
  959:     my $num_parameters = 0;
  960:     my $store_performance_command = 'INSERT INTO '.$performance_table.
  961:         ' VALUES '."\n";
  962:     return ('error',undef) if (! defined($dbh));
  963:     while (my ($current_symb,$param_hash) = each(%student_data)) {
  964:         #
  965:         # make sure the symb is set up properly
  966:         my $symb_id = &get_symb_id($current_symb);
  967:         #
  968:         # Load data into the tables
  969:         while (my ($parameter,$value) = each(%$param_hash)) {
  970:             my $newstring;
  971:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
  972:                 $newstring = "('".join("','",
  973:                                        $symb_id,$student_id,
  974:                                        $parameter)."',".
  975:                                            $dbh->quote($value)."),\n";
  976:                 $num_parameters ++;
  977:                 if ($newstring !~ /''/) {
  978:                     $store_parameters_command .= $newstring;
  979:                     $rows_stored++;
  980:                 }
  981:             }
  982:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
  983:             #
  984:             my $part = $1;
  985:             my $part_id = &get_part_id($part);
  986:             next if (!defined($part_id));
  987:             my $solved  = $value;
  988:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
  989:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
  990:             my $award   = $param_hash->{'resource.'.$part.'.award'};
  991:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
  992:             my $timestamp = $param_hash->{'timestamp'};
  993:             #
  994:             $solved      = '' if (! defined($solved));
  995:             $tries       = '' if (! defined($tries));
  996:             $awarded     = '' if (! defined($awarded));
  997:             $award       = '' if (! defined($award));
  998:             $awarddetail = '' if (! defined($awarddetail));
  999:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,$part,
 1000:                                    $solved,$tries,$awarded,$award,
 1001:                                    $awarddetail,$timestamp)."'),\n";
 1002:             $store_performance_command .= $newstring;
 1003:             $rows_stored++;
 1004:         }
 1005:     }
 1006:     chop $store_parameters_command;
 1007:     chop $store_parameters_command;
 1008:     chop $store_performance_command;
 1009:     chop $store_performance_command;
 1010:     my $start = Time::HiRes::time;
 1011:     $dbh->do($store_parameters_command) if ($num_parameters>0);
 1012:     if ($dbh->err()) {
 1013:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
 1014:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
 1015:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
 1016:         &Apache::lonnet::logthis('student_id = '.$student_id);
 1017:         $returnstatus = 'error: unable to insert parameters into database';
 1018:         return ($returnstatus,\%student_data);
 1019:     }
 1020:     $dbh->do($store_performance_command);
 1021:     if ($dbh->err()) {
 1022:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
 1023:         &Apache::lonnet::logthis('command = '.$store_performance_command);
 1024:         $returnstatus = 'error: unable to insert performance into database';
 1025:         return ($returnstatus,\%student_data);
 1026:     }
 1027:     $elapsed += Time::HiRes::time - $start;
 1028:     #
 1029:     # Set the students update time
 1030:     &Apache::lonmysql::replace_row($studentdata_table,
 1031:                                    [$student_id,$time_of_retrieval,undef,undef]);
 1032:     return ($returnstatus,\%student_data);
 1033: }
 1034: 
 1035: ################################################
 1036: ################################################
 1037: 
 1038: =pod
 1039: 
 1040: =item &ensure_current_data()
 1041: 
 1042: Input: $sname, $sdom, $courseid
 1043: 
 1044: Output: $status, $data
 1045: 
 1046: This routine ensures the data for a given student is up to date.  It calls
 1047: &init_dbs() if the tables do not exist.  The $studentdata_table is queried
 1048: to determine the time of the last update.  If the students data is out of
 1049: date, &update_student_data() is called.  The return values from the call
 1050: to &update_student_data() are returned.
 1051: 
 1052: =cut
 1053: 
 1054: ################################################
 1055: ################################################
 1056: sub ensure_current_data {
 1057:     my ($sname,$sdom,$courseid) = @_;
 1058:     my $status = 'okay';   # return value
 1059:     #
 1060:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1061:     # 
 1062:     # Clean out package variables
 1063:     &setup_table_names($courseid);
 1064:     #
 1065:     # if the tables do not exist, make them
 1066:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
 1067:     my ($found_symb,$found_student,$found_part,$found_studentdata,
 1068:         $found_performance,$found_parameters);
 1069:     foreach (@CurrentTable) {
 1070:         $found_symb        = 1 if ($_ eq $symb_table);
 1071:         $found_student     = 1 if ($_ eq $student_table);
 1072:         $found_part        = 1 if ($_ eq $part_table);
 1073:         $found_studentdata = 1 if ($_ eq $studentdata_table);
 1074:         $found_performance = 1 if ($_ eq $performance_table);
 1075:         $found_parameters  = 1 if ($_ eq $parameters_table);
 1076:     }
 1077:     if (!$found_symb        || !$found_studentdata || 
 1078:         !$found_student     || !$found_part   ||
 1079:         !$found_performance || !$found_parameters) {
 1080:         if (&init_dbs($courseid)) {
 1081:             return ('error',undef);
 1082:         }
 1083:     }
 1084:     #
 1085:     # Get the update time for the user
 1086:     my $updatetime = 0;
 1087:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
 1088:         ($sdom,$sname,$courseid.'.db',
 1089:          $Apache::lonnet::perlvar{'lonUsersDir'});
 1090:     #
 1091:     my $student_id = &get_student_id($sname,$sdom);
 1092:     my @Result = &Apache::lonmysql::get_rows($studentdata_table,
 1093:                                              "student_id ='$student_id'");
 1094:     my $data = undef;
 1095:     if (@Result) {
 1096:         $updatetime = $Result[0]->[1];
 1097:     }
 1098:     if ($modifiedtime > $updatetime) {
 1099:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
 1100:     }
 1101:     return ($status,$data);
 1102: }
 1103: 
 1104: ################################################
 1105: ################################################
 1106: 
 1107: =pod
 1108: 
 1109: =item &get_student_data_from_performance_cache()
 1110: 
 1111: Input: $sname, $sdom, $symb, $courseid
 1112: 
 1113: Output: hash reference containing the data for the given student.
 1114: If $symb is undef, all the students data is returned.
 1115: 
 1116: This routine is the heart of the local caching system.  See the description
 1117: of $performance_table, $symb_table, $student_table, and $part_table.  The
 1118: main task is building the MySQL request.  The tables appear in the request
 1119: in the order in which they should be parsed by MySQL.  When searching
 1120: on a student the $student_table is used to locate the 'student_id'.  All
 1121: rows in $performance_table which have a matching 'student_id' are returned,
 1122: with data from $part_table and $symb_table which match the entries in
 1123: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
 1124: the $symb_table is processed first, with matching rows grabbed from 
 1125: $performance_table and filled in from $part_table and $student_table in
 1126: that order.  
 1127: 
 1128: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
 1129: interesting, especially if you play with the order the tables are listed.  
 1130: 
 1131: =cut
 1132: 
 1133: ################################################
 1134: ################################################
 1135: sub get_student_data_from_performance_cache {
 1136:     my ($sname,$sdom,$symb,$courseid)=@_;
 1137:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
 1138:     &setup_table_names($courseid);
 1139:     #
 1140:     # Return hash
 1141:     my $studentdata;
 1142:     #
 1143:     my $dbh = &Apache::lonmysql::get_dbh();
 1144:     my $request = "SELECT ".
 1145:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
 1146:             "a.timestamp ";
 1147:     if (defined($student)) {
 1148:         $request .= "FROM $student_table AS b ".
 1149:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
 1150: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
 1151:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
 1152:                 "WHERE student='$student'";
 1153:         if (defined($symb) && $symb ne '') {
 1154:             $request .= " AND d.symb=".$dbh->quote($symb);
 1155:         }
 1156:     } elsif (defined($symb) && $symb ne '') {
 1157:         $request .= "FROM $symb_table as d ".
 1158:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
 1159: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
 1160:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
 1161:                 "WHERE symb='".$dbh->quote($symb)."'";
 1162:     }
 1163:     my $starttime = Time::HiRes::time;
 1164:     my $rows_retrieved = 0;
 1165:     my $sth = $dbh->prepare($request);
 1166:     $sth->execute();
 1167:     if ($sth->err()) {
 1168:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
 1169:         &Apache::lonnet::logthis("\n".$request."\n");
 1170:         &Apache::lonnet::logthis("error is:".$sth->errstr());
 1171:         return undef;
 1172:     }
 1173:     foreach my $row (@{$sth->fetchall_arrayref}) {
 1174:         $rows_retrieved++;
 1175:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
 1176:             (@$row);
 1177:         my $base = 'resource.'.$part;
 1178:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
 1179:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
 1180:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
 1181:         $studentdata->{$symb}->{$base.'.award'}   = $award;
 1182:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
 1183:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
 1184:     }
 1185:     if (defined($symb) && $symb ne '') {
 1186:         $studentdata = $studentdata->{$symb};
 1187:     }
 1188:     return $studentdata;
 1189: }
 1190: 
 1191: ################################################
 1192: ################################################
 1193: 
 1194: =pod
 1195: 
 1196: =item &get_current_state()
 1197: 
 1198: Input: $sname,$sdom,$symb,$courseid
 1199: 
 1200: Output: Described below
 1201: 
 1202: Retrieve the current status of a students performance.  $sname and
 1203: $sdom are the only required parameters.  If $symb is undef the results
 1204: of an &Apache::lonnet::currentdump() will be returned.  
 1205: If $courseid is undef it will be retrieved from the environment.
 1206: 
 1207: The return structure is based on &Apache::lonnet::currentdump.  If
 1208: $symb is unspecified, all the students data is returned in a hash of
 1209: the form:
 1210: ( 
 1211:   symb1 => { param1 => value1, param2 => value2 ... },
 1212:   symb2 => { param1 => value1, param2 => value2 ... },
 1213: )
 1214: 
 1215: If $symb is specified, a hash of 
 1216: (
 1217:   param1 => value1, 
 1218:   param2 => value2,
 1219: )
 1220: is returned.
 1221: 
 1222: If no data is found for $symb, or if the student has no performance data,
 1223: an empty list is returned.
 1224: 
 1225: =cut
 1226: 
 1227: ################################################
 1228: ################################################
 1229: sub get_current_state {
 1230:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
 1231:     #
 1232:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1233:     #
 1234:     return () if (! defined($sname) || ! defined($sdom));
 1235:     #
 1236:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
 1237: #    &Apache::lonnet::logthis
 1238: #        ('sname = '.$sname.
 1239: #         ' domain = '.$sdom.
 1240: #         ' status = '.$status.
 1241: #         ' data is '.(defined($data)?'defined':'undefined'));
 1242: #    while (my ($symb,$hash) = each(%$data)) {
 1243: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
 1244: #        while (my ($key,$value) = each (%$hash)) {
 1245: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
 1246: #        }
 1247: #    }
 1248:     #
 1249:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
 1250:         return %{$data->{$symb}};
 1251:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
 1252:         return %$data;
 1253:     } 
 1254:     if ($status eq 'no data') {
 1255:         return ();
 1256:     } else {
 1257:         if ($status ne 'okay' && $status ne '') {
 1258:             &Apache::lonnet::logthis('status = '.$status);
 1259:             return ();
 1260:         }
 1261:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
 1262:                                                       $symb,$courseid);
 1263:         return %$returnhash if (defined($returnhash));
 1264:     }
 1265:     return ();
 1266: }
 1267: 
 1268: ################################################
 1269: ################################################
 1270: 
 1271: =pod
 1272: 
 1273: =item &get_problem_statistics()
 1274: 
 1275: Gather data on a given problem.  The database is assumed to be 
 1276: populated and all local caching variables are assumed to be set
 1277: properly.  This means you need to call &ensure_current_data for
 1278: the students you are concerned with prior to calling this routine.
 1279: 
 1280: Inputs: $students, $symb, $part, $courseid
 1281: 
 1282: =over 4
 1283: 
 1284: =item $students is an array of hash references.  
 1285: Each hash must contain at least the 'username' and 'domain' of a student.
 1286: 
 1287: =item $symb is the symb for the problem.
 1288: 
 1289: =item $part is the part id you need statistics for
 1290: 
 1291: =item $courseid is the course id, of course!
 1292: 
 1293: =back
 1294: 
 1295: Outputs: See the code for up to date information.  A hash reference is
 1296: returned.  The hash has the following keys defined:
 1297: 
 1298: =over 4
 1299: 
 1300: =item num_students The number of students attempting the problem
 1301:       
 1302: =item tries The total number of tries for the students
 1303:       
 1304: =item max_tries The maximum number of tries taken
 1305:       
 1306: =item mean_tries The average number of tries
 1307:       
 1308: =item num_solved The number of students able to solve the problem
 1309:       
 1310: =item num_override The number of students whose answer is 'correct_by_override'
 1311:       
 1312: =item deg_of_diff The degree of difficulty of the problem
 1313:       
 1314: =item std_tries The standard deviation of the number of tries
 1315:       
 1316: =item skew_tries The skew of the number of tries
 1317: 
 1318: =item per_wrong The number of students attempting the problem who were not
 1319: able to answer it correctly.
 1320: 
 1321: =back
 1322: 
 1323: =cut
 1324: 
 1325: ################################################
 1326: ################################################
 1327: sub get_problem_statistics {
 1328:     my ($students,$symb,$part,$courseid) = @_;
 1329:     return if (! defined($symb) || ! defined($part));
 1330:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1331:     #
 1332:     my $symb_id = &get_symb_id($symb);
 1333:     my $part_id = &get_part_id($part);
 1334:     my $stats_table = $courseid.'_problem_stats';
 1335:     #
 1336:     my $dbh = &Apache::lonmysql::get_dbh();
 1337:     return undef if (! defined($dbh));
 1338:     #
 1339:     # A) Number of Students attempting problem
 1340:     # B) Total number of tries of students attempting problem
 1341:     # C) Mod (largest number of tries for solving the problem)
 1342:     # D) Mean (average number of tries for solving the problem)
 1343:     # E) Number of students to solve the problem
 1344:     # F) Number of students to solve the problem by override
 1345:     # G) Number of students unable to solve the problem
 1346:     # H) Degree of difficulty : 1-(E+F)/B
 1347:     # I) Standard deviation of number of tries
 1348:     # J) Skew of tries: sqrt(sum(Xi-D)^3)/A
 1349:     #
 1350:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1351:     my $request = 
 1352:         'CREATE TEMPORARY TABLE '.$stats_table.
 1353:             ' SELECT student_id,solved,award,tries FROM '.$performance_table.
 1354:                 ' WHERE symb_id='.$symb_id.' AND part_id='.$part_id;
 1355:     if (defined($students)) {
 1356:         $request .= ' AND ('.
 1357:             join(' OR ', map {'student_id='.
 1358:                                   &get_student_id($_->{'username'},
 1359:                                                   $_->{'domain'})
 1360:                                   } @$students
 1361:                  ).')';
 1362:     }
 1363: #    &Apache::lonnet::logthis($request);
 1364:     $dbh->do($request);
 1365:     my ($num,$tries,$mod,$mean,$STD) = &execute_SQL_request
 1366:         ($dbh,
 1367:          'SELECT COUNT(*),SUM(tries),MAX(tries),AVG(tries),STD(tries) FROM '.
 1368:          $stats_table);
 1369:     my ($Solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
 1370:                                         $stats_table.
 1371:                                         " WHERE solved='correct_by_student'");
 1372:     my ($solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
 1373:                                         $stats_table.
 1374:                                         " WHERE solved='correct_by_override'");
 1375:     $num    = 0 if (! defined($num));
 1376:     $tries  = 0 if (! defined($tries));
 1377:     $mod    = 0 if (! defined($mod));
 1378:     $STD    = 0 if (! defined($STD));
 1379:     $Solved = 0 if (! defined($Solved));
 1380:     $solved = 0 if (! defined($solved));
 1381:     #
 1382:     my $DegOfDiff = 'nan';
 1383:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
 1384: 
 1385:     my $SKEW = 'nan';
 1386:     my $wrongpercent = 0;
 1387:     if ($num > 0) {
 1388:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
 1389:                                      'POWER(tries - '.$STD.',3)'.
 1390:                                      '))/'.$num.' FROM '.$stats_table);
 1391:         $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
 1392:     }
 1393:     #
 1394:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1395:     #
 1396:     # Store in metadata
 1397:     #
 1398:     if ($num) {
 1399: 	my %storestats=();
 1400: 
 1401:         my $urlres=(&Apache::lonnet::decode_symb($symb))[2];
 1402: 
 1403: 	$storestats{$courseid.'___'.$urlres.'___timestamp'}=time;       
 1404: 	$storestats{$courseid.'___'.$urlres.'___stdno'}=$num;
 1405: 	$storestats{$courseid.'___'.$urlres.'___avetries'}=$mean;	   
 1406: 	$storestats{$courseid.'___'.$urlres.'___difficulty'}=$DegOfDiff;
 1407: 
 1408: 	$urlres=~/^(\w+)\/(\w+)/; 
 1409: 	&Apache::lonnet::put('nohist_resevaldata',\%storestats,$1,$2); 
 1410:     }
 1411:     #
 1412:     # Return result
 1413:     #
 1414:     return { num_students => $num,
 1415:              tries        => $tries,
 1416:              max_tries    => $mod,
 1417:              mean_tries   => $mean,
 1418:              std_tries    => $STD,
 1419:              skew_tries   => $SKEW,
 1420:              num_solved   => $Solved,
 1421:              num_override => $solved,
 1422:              per_wrong    => $wrongpercent,
 1423:              deg_of_diff  => $DegOfDiff };
 1424: }
 1425: 
 1426: sub execute_SQL_request {
 1427:     my ($dbh,$request)=@_;
 1428: #    &Apache::lonnet::logthis($request);
 1429:     my $sth = $dbh->prepare($request);
 1430:     $sth->execute();
 1431:     my $row = $sth->fetchrow_arrayref();
 1432:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
 1433:         return @$row;
 1434:     }
 1435:     return ();
 1436: }
 1437: 
 1438: 
 1439: ################################################
 1440: ################################################
 1441: 
 1442: =pod
 1443: 
 1444: =item &setup_table_names()
 1445: 
 1446: input: course id
 1447: 
 1448: output: none
 1449: 
 1450: Cleans up the package variables for local caching.
 1451: 
 1452: =cut
 1453: 
 1454: ################################################
 1455: ################################################
 1456: sub setup_table_names {
 1457:     my ($courseid) = @_;
 1458:     if (! defined($courseid)) {
 1459:         $courseid = $ENV{'request.course.id'};
 1460:     }
 1461:     #
 1462:     if (! defined($current_course) || $current_course ne $courseid) {
 1463:         # Clear out variables
 1464:         $have_read_part_table = 0;
 1465:         undef(%ids_by_part);
 1466:         undef(%parts_by_id);
 1467:         $have_read_symb_table = 0;
 1468:         undef(%ids_by_symb);
 1469:         undef(%symbs_by_id);
 1470:         $have_read_student_table = 0;
 1471:         undef(%ids_by_student);
 1472:         undef(%students_by_id);
 1473:         #
 1474:         $current_course = $courseid;
 1475:     }
 1476:     #
 1477:     # Set up database names
 1478:     my $base_id = $courseid;
 1479:     $symb_table        = $base_id.'_'.'symb';
 1480:     $part_table        = $base_id.'_'.'part';
 1481:     $student_table     = $base_id.'_'.'student';
 1482:     $studentdata_table = $base_id.'_'.'studentdata';
 1483:     $performance_table = $base_id.'_'.'performance';
 1484:     $parameters_table  = $base_id.'_'.'parameters';
 1485:     return;
 1486: }
 1487: 
 1488: ################################################
 1489: ################################################
 1490: 
 1491: =pod
 1492: 
 1493: =back
 1494: 
 1495: =item End of Local Data Caching Subroutines
 1496: 
 1497: =cut
 1498: 
 1499: ################################################
 1500: ################################################
 1501: 
 1502: 
 1503: }
 1504: ################################################
 1505: ################################################
 1506: 
 1507: =pod
 1508: 
 1509: =head3 Classlist Subroutines
 1510: 
 1511: =item &get_classlist();
 1512: 
 1513: Retrieve the classist of a given class or of the current class.  Student
 1514: information is returned from the classlist.db file and, if needed,
 1515: from the students environment.
 1516: 
 1517: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
 1518: and course number, respectively).  Any omitted arguments will be taken 
 1519: from the current environment ($ENV{'request.course.id'},
 1520: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
 1521: 
 1522: Returns a reference to a hash which contains:
 1523:  keys    '$sname:$sdom'
 1524:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status]
 1525: 
 1526: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
 1527: as indices into the returned list to future-proof clients against
 1528: changes in the list order.
 1529: 
 1530: =cut
 1531: 
 1532: ################################################
 1533: ################################################
 1534: 
 1535: sub CL_SDOM     { return 0; }
 1536: sub CL_SNAME    { return 1; }
 1537: sub CL_END      { return 2; }
 1538: sub CL_START    { return 3; }
 1539: sub CL_ID       { return 4; }
 1540: sub CL_SECTION  { return 5; }
 1541: sub CL_FULLNAME { return 6; }
 1542: sub CL_STATUS   { return 7; }
 1543: 
 1544: sub get_classlist {
 1545:     my ($cid,$cdom,$cnum) = @_;
 1546:     $cid = $cid || $ENV{'request.course.id'};
 1547:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
 1548:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
 1549:     my $now = time;
 1550:     #
 1551:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
 1552:     while (my ($student,$info) = each(%classlist)) {
 1553:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
 1554:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
 1555:             return undef;
 1556:         }
 1557:         my ($sname,$sdom) = split(/:/,$student);
 1558:         my @Values = split(/:/,$info);
 1559:         my ($end,$start,$id,$section,$fullname);
 1560:         if (@Values > 2) {
 1561:             ($end,$start,$id,$section,$fullname) = @Values;
 1562:         } else { # We have to get the data ourselves
 1563:             ($end,$start) = @Values;
 1564:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
 1565:             my %info=&Apache::lonnet::get('environment',
 1566:                                           ['firstname','middlename',
 1567:                                            'lastname','generation','id'],
 1568:                                           $sdom, $sname);
 1569:             my ($tmp) = keys(%info);
 1570:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 1571:                 $fullname = 'not available';
 1572:                 $id = 'not available';
 1573:                 &Apache::lonnet::logthis('unable to retrieve environment '.
 1574:                                          'for '.$sname.':'.$sdom);
 1575:             } else {
 1576:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
 1577:                                                        firstname middlename/});
 1578:                 $id = $info{'id'};
 1579:             }
 1580:             # Update the classlist with this students information
 1581:             if ($fullname ne 'not available') {
 1582:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
 1583:                 my $reply=&Apache::lonnet::cput('classlist',
 1584:                                                 {$student => $enrolldata},
 1585:                                                 $cdom,$cnum);
 1586:                 if ($reply !~ /^(ok|delayed)/) {
 1587:                     &Apache::lonnet::logthis('Unable to update classlist for '.
 1588:                                              'student '.$sname.':'.$sdom.
 1589:                                              ' error:'.$reply);
 1590:                 }
 1591:             }
 1592:         }
 1593:         my $status='Expired';
 1594:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
 1595:             $status='Active';
 1596:         }
 1597:         $classlist{$student} = 
 1598:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
 1599:     }
 1600:     if (wantarray()) {
 1601:         return (\%classlist,['domain','username','end','start','id',
 1602:                              'section','fullname','status']);
 1603:     } else {
 1604:         return \%classlist;
 1605:     }
 1606: }
 1607: 
 1608: # ----- END HELPER FUNCTIONS --------------------------------------------
 1609: 
 1610: 1;
 1611: __END__
 1612: 
 1613: 

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