Annotation of loncom/interface/loncoursedata.pm, revision 1.153

1.1       stredwic    1: # The LearningOnline Network with CAPA
                      2: #
1.153   ! albertel    3: # $Id: loncoursedata.pm,v 1.152 2006/02/04 20:03:30 bowersj2 Exp $
1.1       stredwic    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: 
1.22      stredwic   37: Set of functions that download and process student and course information.
1.1       stredwic   38: 
                     39: =head1 PACKAGES USED
                     40: 
                     41:  Apache::Constants qw(:common :http)
                     42:  Apache::lonnet()
1.22      stredwic   43:  Apache::lonhtmlcommon
1.1       stredwic   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);
1.146     albertel   53: use Apache::lonnet;
1.13      stredwic   54: use Apache::lonhtmlcommon;
1.57      matthew    55: use Time::HiRes;
                     56: use Apache::lonmysql;
1.1       stredwic   57: use HTML::TokeParser;
                     58: use GDBM_File;
                     59: 
                     60: =pod
                     61: 
                     62: =head1 DOWNLOAD INFORMATION
                     63: 
1.22      stredwic   64: This section contains all the functions that get data from other servers 
                     65: and/or itself.
1.1       stredwic   66: 
                     67: =cut
                     68: 
1.4       stredwic   69: sub LoadDiscussion {
1.13      stredwic   70:     my ($courseID)=@_;
1.5       minaeibi   71:     my %Discuss=();
                     72:     my %contrib=&Apache::lonnet::dump(
                     73:                 $courseID,
1.146     albertel   74:                 $env{'course.'.$courseID.'.domain'},
                     75:                 $env{'course.'.$courseID.'.num'});
1.5       minaeibi   76: 				 
                     77:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
                     78: 
1.4       stredwic   79:     foreach my $temp(keys %contrib) {
                     80: 	if ($temp=~/^version/) {
                     81: 	    my $ver=$contrib{$temp};
                     82: 	    my ($dummy,$prb)=split(':',$temp);
                     83: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
                     84: 		my $name=$contrib{"$idx:$prb:sendername"};
1.5       minaeibi   85: 		$Discuss{"$name:$prb"}=$idx;	
1.4       stredwic   86: 	    }
                     87: 	}
                     88:     }       
1.5       minaeibi   89: 
                     90:     return \%Discuss;
1.1       stredwic   91: }
                     92: 
1.71      matthew    93: ################################################
                     94: ################################################
                     95: 
                     96: =pod
                     97: 
1.47      matthew    98: =item &make_into_hash($values);
                     99: 
                    100: Returns a reference to a hash as described by $values.  $values is
                    101: assumed to be the result of 
1.57      matthew   102:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
1.47      matthew   103: 
                    104: This is a helper function for get_current_state.
                    105: 
                    106: =cut
                    107: 
                    108: ################################################
                    109: ################################################
                    110: sub make_into_hash {
                    111:     my $values = shift;
                    112:     my %tmp = map { &Apache::lonnet::unescape($_); }
                    113:                                            split(':',$values);
                    114:     return \%tmp;
                    115: }
                    116: 
                    117: 
                    118: ################################################
                    119: ################################################
                    120: 
                    121: =pod
                    122: 
1.57      matthew   123: =head1 LOCAL DATA CACHING SUBROUTINES
                    124: 
                    125: The local caching is done using MySQL.  There is no fall-back implementation
                    126: if MySQL is not running.
                    127: 
                    128: The programmers interface is to call &get_current_state() or some other
                    129: primary interface subroutine (described below).  The internals of this 
                    130: storage system are documented here.
                    131: 
                    132: There are six tables used to store student performance data (the results of
                    133: a dumpcurrent).  Each of these tables is created in MySQL with a name of
                    134: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
                    135: for the table.  The tables and their purposes are described below.
                    136: 
                    137: Some notes before we get started.
                    138: 
                    139: Each table must have a PRIMARY KEY, which is a column or set of columns which
                    140: will serve to uniquely identify a row of data.  NULL is not allowed!
                    141: 
                    142: INDEXes work best on integer data.
                    143: 
                    144: JOIN is used to combine data from many tables into one output.
                    145: 
                    146: lonmysql.pm is used for some of the interface, specifically the table creation
                    147: calls.  The inserts are done in bulk by directly calling the database handler.
                    148: The SELECT ... JOIN statement used to retrieve the data does not have an
                    149: interface in lonmysql.pm and I shudder at the thought of writing one.
                    150: 
                    151: =head3 Table Descriptions
                    152: 
                    153: =over 4
                    154: 
1.89      matthew   155: =item Tables used to store meta information
                    156: 
                    157: The following tables hold data required to keep track of the current status
                    158: of a students data in the tables or to look up the students data in the tables.
                    159: 
                    160: =over 4
                    161: 
1.57      matthew   162: =item $symb_table
                    163: 
                    164: The symb_table has two columns.  The first is a 'symb_id' and the second
                    165: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
                    166: automatically by MySQL so inserts should be done on this table with an
                    167: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
                    168: 
                    169: =item $part_table
                    170: 
                    171: The part_table has two columns.  The first is a 'part_id' and the second
                    172: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
                    173: generated automatically by MySQL so inserts should be done on this table with
                    174: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
                    175: characters) and a KEY on 'part_id'.
                    176: 
                    177: =item $student_table
                    178: 
1.113     matthew   179: The student_table has 7 columns.  The first is a 'student_id' assigned by 
                    180: MySQL.  The second is 'student' which is username:domain.  The third through
                    181: fifth are 'section', 'status' (enrollment status), and 'classification' 
                    182: (to be used in the future).  The sixth and seventh ('updatetime' and 
                    183: 'fullupdatetime') contain the time of last update and full update of student
                    184: data.  This table has its PRIMARY KEY on the 'student_id' column and is indexed
                    185: on 'student', 'section', and 'status'.
1.89      matthew   186: 
                    187: =back 
                    188: 
                    189: =item Tables used to store current status data
                    190: 
                    191: The following tables store data only about the students current status on 
                    192: a problem, meaning only the data related to the last attempt on a problem.
                    193: 
                    194: =over 4
1.57      matthew   195: 
                    196: =item $performance_table
                    197: 
                    198: The performance_table has 9 columns.  The first three are 'symb_id', 
                    199: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
                    200: and are directly related to the $symb_table, $student_table, and $part_table
                    201: described above.  MySQL does better indexing on numeric items than text,
                    202: so we use these three "index tables".  The remaining columns are
                    203: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
                    204: These are either the MySQL type TINYTEXT or various integers ('tries' and 
                    205: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
                    206: For use of this table, see the functions described below.
                    207: 
                    208: =item $parameters_table
                    209: 
                    210: The parameters_table holds the data that does not fit neatly into the
                    211: performance_table.  The parameters table has four columns: 'symb_id',
                    212: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
                    213: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
                    214: limited to 255 characters.  'value' is limited to 64k characters.
                    215: 
                    216: =back
                    217: 
1.89      matthew   218: =item Tables used for storing historic data
                    219: 
                    220: The following tables are used to store almost all of the transactions a student
                    221: has made on a homework problem.  See loncapa/docs/homework/datastorage for 
                    222: specific information about each of the parameters stored.  
                    223: 
                    224: =over 4
                    225: 
                    226: =item $fulldump_response_table
                    227: 
                    228: The response table holds data (documented in loncapa/docs/homework/datastorage)
                    229: associated with a particular response id which is stored when a student 
                    230: attempts a problem.  The following are the columns of the table, in order:
                    231: 'symb_id','part_id','response_id','student_id','transaction','tries',
1.93      matthew   232: 'awarddetail', 'response_specific' (data particular to the response
1.89      matthew   233: type), 'response_specific_value', and 'submission (the text of the students
                    234: submission).  The primary key is based on the first five columns listed above.
                    235: 
                    236: =item $fulldump_part_table
                    237: 
                    238: The part table holds data (documented in loncapa/docs/homework/datastorage)
                    239: associated with a particular part id which is stored when a student attempts
                    240: a problem.  The following are the columns of the table, in order:
                    241: 'symb_id','part_id','student_id','transaction','tries','award','awarded',
                    242: and 'previous'.  The primary key is based on the first five columns listed 
                    243: above.
                    244: 
                    245: =item $fulldump_timestamp_table
                    246: 
                    247: The timestamp table holds the timestamps of the transactions which are
                    248: stored in $fulldump_response_table and $fulldump_part_table.  This data is
                    249: about both the response and part data.  Columns: 'symb_id','student_id',
                    250: 'transaction', and 'timestamp'.  
                    251: The primary key is based on the first 3 columns.
                    252: 
1.127     matthew   253: =item $weight_table
                    254: 
                    255: The weight table holds the weight for the problems used in the class.
                    256: Whereas the weight of a problem can vary by section and student the data
                    257: here is applied to the class as a whole.
                    258: Columns: 'symb_id','part_id','response_id','weight'.
                    259: 
1.89      matthew   260: =back
                    261: 
                    262: =back
                    263: 
1.57      matthew   264: =head3 Important Subroutines
                    265: 
                    266: Here is a brief overview of the subroutines which are likely to be of 
                    267: interest:
                    268: 
                    269: =over 4
                    270: 
                    271: =item &get_current_state(): programmers interface.
                    272: 
                    273: =item &init_dbs(): table creation
                    274: 
                    275: =item &update_student_data(): data storage calls
                    276: 
                    277: =item &get_student_data_from_performance_cache(): data retrieval
                    278: 
                    279: =back
                    280: 
                    281: =head3 Main Documentation
                    282: 
                    283: =over 4
                    284: 
                    285: =cut
                    286: 
                    287: ################################################
                    288: ################################################
                    289: 
                    290: ################################################
                    291: ################################################
1.89      matthew   292: { # Begin scope of table identifiers
1.57      matthew   293: 
                    294: my $current_course ='';
                    295: my $symb_table;
                    296: my $part_table;
                    297: my $student_table;
                    298: my $performance_table;
                    299: my $parameters_table;
1.89      matthew   300: my $fulldump_response_table;
                    301: my $fulldump_part_table;
                    302: my $fulldump_timestamp_table;
1.127     matthew   303: my $weight_table;
1.57      matthew   304: 
1.89      matthew   305: my @Tables;
1.57      matthew   306: ################################################
                    307: ################################################
                    308: 
                    309: =pod
                    310: 
                    311: =item &init_dbs()
                    312: 
                    313: Input: course id
                    314: 
                    315: Output: 0 on success, positive integer on error
                    316: 
                    317: This routine issues the calls to lonmysql to create the tables used to
                    318: store student data.
                    319: 
                    320: =cut
                    321: 
                    322: ################################################
                    323: ################################################
                    324: sub init_dbs {
1.134     matthew   325:     my ($courseid,$drop) = @_;
1.57      matthew   326:     &setup_table_names($courseid);
                    327:     #
1.73      matthew   328:     # Drop any of the existing tables
1.134     matthew   329:     if ($drop) {
                    330:         foreach my $table (@Tables) {
                    331:             &Apache::lonmysql::drop_table($table);
                    332:         }
1.73      matthew   333:     }
                    334:     #
1.57      matthew   335:     # Note - changes to this table must be reflected in the code that 
                    336:     # stores the data (calls &Apache::lonmysql::store_row with this table
                    337:     # id
                    338:     my $symb_table_def = {
                    339:         id => $symb_table,
                    340:         permanent => 'no',
                    341:         columns => [{ name => 'symb_id',
                    342:                       type => 'MEDIUMINT UNSIGNED',
                    343:                       restrictions => 'NOT NULL',
                    344:                       auto_inc     => 'yes', },
                    345:                     { name => 'symb',
                    346:                       type => 'MEDIUMTEXT',
                    347:                       restrictions => 'NOT NULL'},
                    348:                     ],
                    349:         'PRIMARY KEY' => ['symb_id'],
                    350:     };
                    351:     #
                    352:     my $part_table_def = {
                    353:         id => $part_table,
                    354:         permanent => 'no',
                    355:         columns => [{ name => 'part_id',
                    356:                       type => 'MEDIUMINT UNSIGNED',
                    357:                       restrictions => 'NOT NULL',
                    358:                       auto_inc     => 'yes', },
                    359:                     { name => 'part',
1.132     matthew   360:                       type => 'VARCHAR(100) BINARY',
1.57      matthew   361:                       restrictions => 'NOT NULL'},
                    362:                     ],
                    363:         'PRIMARY KEY' => ['part (100)'],
                    364:         'KEY' => [{ columns => ['part_id']},],
                    365:     };
                    366:     #
                    367:     my $student_table_def = {
                    368:         id => $student_table,
                    369:         permanent => 'no',
                    370:         columns => [{ name => 'student_id',
                    371:                       type => 'MEDIUMINT UNSIGNED',
                    372:                       restrictions => 'NOT NULL',
                    373:                       auto_inc     => 'yes', },
                    374:                     { name => 'student',
1.132     matthew   375:                       type => 'VARCHAR(100) BINARY',
1.113     matthew   376:                       restrictions => 'NOT NULL UNIQUE'},
                    377:                     { name => 'section',
1.132     matthew   378:                       type => 'VARCHAR(100) BINARY',
1.113     matthew   379:                       restrictions => 'NOT NULL'},
                    380:                     { name => 'status',
1.132     matthew   381:                       type => 'VARCHAR(15) BINARY',
1.57      matthew   382:                       restrictions => 'NOT NULL'},
1.85      matthew   383:                     { name => 'classification',
1.132     matthew   384:                       type => 'VARCHAR(100) BINARY', },
1.57      matthew   385:                     { name => 'updatetime',
1.89      matthew   386:                       type => 'INT UNSIGNED'},
                    387:                     { name => 'fullupdatetime',
                    388:                       type => 'INT UNSIGNED'},
1.57      matthew   389:                     ],
1.87      matthew   390:         'PRIMARY KEY' => ['student_id'],
1.113     matthew   391:         'KEY' => [{ columns => ['student (100)',
                    392:                                 'section (100)',
                    393:                                 'status (15)',]},],
1.57      matthew   394:     };
                    395:     #
                    396:     my $performance_table_def = {
                    397:         id => $performance_table,
                    398:         permanent => 'no',
                    399:         columns => [{ name => 'symb_id',
                    400:                       type => 'MEDIUMINT UNSIGNED',
                    401:                       restrictions => 'NOT NULL'  },
                    402:                     { name => 'student_id',
                    403:                       type => 'MEDIUMINT UNSIGNED',
                    404:                       restrictions => 'NOT NULL'  },
                    405:                     { name => 'part_id',
                    406:                       type => 'MEDIUMINT UNSIGNED',
                    407:                       restrictions => 'NOT NULL' },
1.73      matthew   408:                     { name => 'part',
1.132     matthew   409:                       type => 'VARCHAR(100) BINARY',
1.73      matthew   410:                       restrictions => 'NOT NULL'},                    
1.57      matthew   411:                     { name => 'solved',
                    412:                       type => 'TINYTEXT' },
                    413:                     { name => 'tries',
                    414:                       type => 'SMALLINT UNSIGNED' },
                    415:                     { name => 'awarded',
1.127     matthew   416:                       type => 'REAL' },
1.57      matthew   417:                     { name => 'award',
                    418:                       type => 'TINYTEXT' },
                    419:                     { name => 'awarddetail',
                    420:                       type => 'TINYTEXT' },
                    421:                     { name => 'timestamp',
                    422:                       type => 'INT UNSIGNED'},
                    423:                     ],
                    424:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
                    425:         'KEY' => [{ columns=>['student_id'] },
                    426:                   { columns=>['symb_id'] },],
                    427:     };
                    428:     #
1.89      matthew   429:     my $fulldump_part_table_def = {
                    430:         id => $fulldump_part_table,
                    431:         permanent => 'no',
                    432:         columns => [
                    433:                     { name => 'symb_id',
                    434:                       type => 'MEDIUMINT UNSIGNED',
                    435:                       restrictions => 'NOT NULL'  },
                    436:                     { name => 'part_id',
                    437:                       type => 'MEDIUMINT UNSIGNED',
                    438:                       restrictions => 'NOT NULL' },
                    439:                     { name => 'student_id',
                    440:                       type => 'MEDIUMINT UNSIGNED',
                    441:                       restrictions => 'NOT NULL'  },
                    442:                     { name => 'transaction',
                    443:                       type => 'MEDIUMINT UNSIGNED',
                    444:                       restrictions => 'NOT NULL' },
                    445:                     { name => 'tries',
                    446:                       type => 'SMALLINT UNSIGNED',
                    447:                       restrictions => 'NOT NULL' },
                    448:                     { name => 'award',
                    449:                       type => 'TINYTEXT' },
                    450:                     { name => 'awarded',
1.127     matthew   451:                       type => 'REAL' },
1.89      matthew   452:                     { name => 'previous',
                    453:                       type => 'SMALLINT UNSIGNED' },
                    454: #                    { name => 'regrader',
                    455: #                      type => 'TINYTEXT' },
                    456: #                    { name => 'afterduedate',
                    457: #                      type => 'TINYTEXT' },
                    458:                     ],
                    459:         'PRIMARY KEY' => ['symb_id','part_id','student_id','transaction'],
                    460:         'KEY' => [
                    461:                   { columns=>['symb_id'] },
                    462:                   { columns=>['part_id'] },
                    463:                   { columns=>['student_id'] },
                    464:                   ],
                    465:     };
                    466:     #
                    467:     my $fulldump_response_table_def = {
                    468:         id => $fulldump_response_table,
                    469:         permanent => 'no',
                    470:         columns => [
                    471:                     { name => 'symb_id',
                    472:                       type => 'MEDIUMINT UNSIGNED',
                    473:                       restrictions => 'NOT NULL'  },
                    474:                     { name => 'part_id',
                    475:                       type => 'MEDIUMINT UNSIGNED',
                    476:                       restrictions => 'NOT NULL' },
                    477:                     { name => 'response_id',
                    478:                       type => 'MEDIUMINT UNSIGNED',
                    479:                       restrictions => 'NOT NULL'  },
                    480:                     { name => 'student_id',
                    481:                       type => 'MEDIUMINT UNSIGNED',
                    482:                       restrictions => 'NOT NULL'  },
                    483:                     { name => 'transaction',
                    484:                       type => 'MEDIUMINT UNSIGNED',
                    485:                       restrictions => 'NOT NULL' },
                    486:                     { name => 'awarddetail',
                    487:                       type => 'TINYTEXT' },
                    488: #                    { name => 'message',
1.132     matthew   489: #                      type => 'CHAR BINARY'},
1.89      matthew   490:                     { name => 'response_specific',
                    491:                       type => 'TINYTEXT' },
                    492:                     { name => 'response_specific_value',
                    493:                       type => 'TINYTEXT' },
                    494:                     { name => 'submission',
                    495:                       type => 'TEXT'},
                    496:                     ],
                    497:             'PRIMARY KEY' => ['symb_id','part_id','response_id','student_id',
                    498:                               'transaction'],
                    499:             'KEY' => [
                    500:                       { columns=>['symb_id'] },
                    501:                       { columns=>['part_id','response_id'] },
                    502:                       { columns=>['student_id'] },
                    503:                       ],
                    504:     };
                    505:     my $fulldump_timestamp_table_def = {
                    506:         id => $fulldump_timestamp_table,
                    507:         permanent => 'no',
                    508:         columns => [
                    509:                     { name => 'symb_id',
                    510:                       type => 'MEDIUMINT UNSIGNED',
                    511:                       restrictions => 'NOT NULL'  },
                    512:                     { name => 'student_id',
                    513:                       type => 'MEDIUMINT UNSIGNED',
                    514:                       restrictions => 'NOT NULL'  },
                    515:                     { name => 'transaction',
                    516:                       type => 'MEDIUMINT UNSIGNED',
                    517:                       restrictions => 'NOT NULL' },
                    518:                     { name => 'timestamp',
                    519:                       type => 'INT UNSIGNED'},
                    520:                     ],
                    521:         'PRIMARY KEY' => ['symb_id','student_id','transaction'],
                    522:         'KEY' => [
                    523:                   { columns=>['symb_id'] },
                    524:                   { columns=>['student_id'] },
                    525:                   { columns=>['transaction'] },
                    526:                   ],
                    527:     };
                    528:     #
1.57      matthew   529:     my $parameters_table_def = {
                    530:         id => $parameters_table,
                    531:         permanent => 'no',
                    532:         columns => [{ name => 'symb_id',
                    533:                       type => 'MEDIUMINT UNSIGNED',
                    534:                       restrictions => 'NOT NULL'  },
                    535:                     { name => 'student_id',
                    536:                       type => 'MEDIUMINT UNSIGNED',
                    537:                       restrictions => 'NOT NULL'  },
                    538:                     { name => 'parameter',
                    539:                       type => 'TINYTEXT',
                    540:                       restrictions => 'NOT NULL'  },
                    541:                     { name => 'value',
                    542:                       type => 'MEDIUMTEXT' },
                    543:                     ],
                    544:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
                    545:     };
                    546:     #
1.127     matthew   547:     my $weight_table_def = {
                    548:         id => $weight_table,
                    549:         permanent => 'no',
                    550:         columns => [{ name => 'symb_id',
                    551:                       type => 'MEDIUMINT UNSIGNED',
                    552:                       restrictions => 'NOT NULL'  },
                    553:                     { name => 'part_id',
                    554:                       type => 'MEDIUMINT UNSIGNED',
                    555:                       restrictions => 'NOT NULL'  },
                    556:                     { name => 'weight',
                    557:                       type => 'REAL',
                    558:                       restrictions => 'NOT NULL'  },
                    559:                     ],
                    560:         'PRIMARY KEY' => ['symb_id','part_id'],
                    561:     };
                    562:     #
1.57      matthew   563:     # Create the tables
                    564:     my $tableid;
                    565:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
                    566:     if (! defined($tableid)) {
                    567:         &Apache::lonnet::logthis("error creating symb_table: ".
                    568:                                  &Apache::lonmysql::get_error());
                    569:         return 1;
                    570:     }
                    571:     #
                    572:     $tableid = &Apache::lonmysql::create_table($part_table_def);
                    573:     if (! defined($tableid)) {
                    574:         &Apache::lonnet::logthis("error creating part_table: ".
                    575:                                  &Apache::lonmysql::get_error());
                    576:         return 2;
                    577:     }
                    578:     #
                    579:     $tableid = &Apache::lonmysql::create_table($student_table_def);
                    580:     if (! defined($tableid)) {
                    581:         &Apache::lonnet::logthis("error creating student_table: ".
                    582:                                  &Apache::lonmysql::get_error());
                    583:         return 3;
                    584:     }
                    585:     #
                    586:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
                    587:     if (! defined($tableid)) {
                    588:         &Apache::lonnet::logthis("error creating preformance_table: ".
                    589:                                  &Apache::lonmysql::get_error());
                    590:         return 5;
                    591:     }
                    592:     #
                    593:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
                    594:     if (! defined($tableid)) {
                    595:         &Apache::lonnet::logthis("error creating parameters_table: ".
                    596:                                  &Apache::lonmysql::get_error());
                    597:         return 6;
                    598:     }
1.89      matthew   599:     #
                    600:     $tableid = &Apache::lonmysql::create_table($fulldump_part_table_def);
                    601:     if (! defined($tableid)) {
                    602:         &Apache::lonnet::logthis("error creating fulldump_part_table: ".
                    603:                                  &Apache::lonmysql::get_error());
                    604:         return 7;
                    605:     }
                    606:     #
                    607:     $tableid = &Apache::lonmysql::create_table($fulldump_response_table_def);
                    608:     if (! defined($tableid)) {
                    609:         &Apache::lonnet::logthis("error creating fulldump_response_table: ".
                    610:                                  &Apache::lonmysql::get_error());
                    611:         return 8;
                    612:     }
                    613:     $tableid = &Apache::lonmysql::create_table($fulldump_timestamp_table_def);
                    614:     if (! defined($tableid)) {
                    615:         &Apache::lonnet::logthis("error creating fulldump_timestamp_table: ".
                    616:                                  &Apache::lonmysql::get_error());
                    617:         return 9;
                    618:     }
1.127     matthew   619:     $tableid = &Apache::lonmysql::create_table($weight_table_def);
                    620:     if (! defined($tableid)) {
                    621:         &Apache::lonnet::logthis("error creating weight_table: ".
                    622:                                  &Apache::lonmysql::get_error());
                    623:         return 10;
                    624:     }
1.57      matthew   625:     return 0;
1.70      matthew   626: }
                    627: 
                    628: ################################################
                    629: ################################################
                    630: 
                    631: =pod
                    632: 
                    633: =item &delete_caches()
                    634: 
1.144     matthew   635: This routine drops all the tables associated with a course from the 
                    636: MySQL database.
                    637: 
                    638: Input: course id (optional, determined by environment if omitted) 
                    639: 
                    640: Returns: nothing
                    641: 
1.70      matthew   642: =cut
                    643: 
                    644: ################################################
                    645: ################################################
                    646: sub delete_caches {
                    647:     my $courseid = shift;
1.146     albertel  648:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.70      matthew   649:     #
                    650:     &setup_table_names($courseid);
                    651:     #
                    652:     my $dbh = &Apache::lonmysql::get_dbh();
1.89      matthew   653:     foreach my $table (@Tables) {
1.70      matthew   654:         my $command = 'DROP TABLE '.$table.';';
                    655:         $dbh->do($command);
                    656:         if ($dbh->err) {
                    657:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
                    658:         }
                    659:     }
                    660:     return;
1.57      matthew   661: }
                    662: 
                    663: ################################################
                    664: ################################################
                    665: 
                    666: =pod
                    667: 
                    668: =item &get_part_id()
                    669: 
                    670: Get the MySQL id of a problem part string.
                    671: 
                    672: Input: $part
                    673: 
                    674: Output: undef on error, integer $part_id on success.
                    675: 
                    676: =item &get_part()
                    677: 
                    678: Get the string describing a part from the MySQL id of the problem part.
                    679: 
                    680: Input: $part_id
                    681: 
                    682: Output: undef on error, $part string on success.
                    683: 
                    684: =cut
                    685: 
                    686: ################################################
                    687: ################################################
                    688: 
1.61      matthew   689: my $have_read_part_table = 0;
1.57      matthew   690: my %ids_by_part;
                    691: my %parts_by_id;
                    692: 
                    693: sub get_part_id {
                    694:     my ($part) = @_;
1.61      matthew   695:     $part = 0 if (! defined($part));
                    696:     if (! $have_read_part_table) {
                    697:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    698:         foreach (@Result) {
                    699:             $ids_by_part{$_->[1]}=$_->[0];
                    700:         }
                    701:         $have_read_part_table = 1;
                    702:     }
1.57      matthew   703:     if (! exists($ids_by_part{$part})) {
                    704:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
                    705:         undef(%ids_by_part);
                    706:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    707:         foreach (@Result) {
                    708:             $ids_by_part{$_->[1]}=$_->[0];
                    709:         }
                    710:     }
                    711:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
                    712:     return undef; # error
                    713: }
                    714: 
                    715: sub get_part {
                    716:     my ($part_id) = @_;
                    717:     if (! exists($parts_by_id{$part_id})  || 
                    718:         ! defined($parts_by_id{$part_id}) ||
                    719:         $parts_by_id{$part_id} eq '') {
                    720:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    721:         foreach (@Result) {
                    722:             $parts_by_id{$_->[0]}=$_->[1];
                    723:         }
                    724:     }
                    725:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
                    726:     return undef; # error
                    727: }
                    728: 
                    729: ################################################
                    730: ################################################
                    731: 
                    732: =pod
                    733: 
                    734: =item &get_symb_id()
                    735: 
                    736: Get the MySQL id of a symb.
                    737: 
                    738: Input: $symb
                    739: 
                    740: Output: undef on error, integer $symb_id on success.
                    741: 
                    742: =item &get_symb()
                    743: 
                    744: Get the symb associated with a MySQL symb_id.
                    745: 
                    746: Input: $symb_id
                    747: 
                    748: Output: undef on error, $symb on success.
                    749: 
                    750: =cut
                    751: 
                    752: ################################################
                    753: ################################################
                    754: 
1.61      matthew   755: my $have_read_symb_table = 0;
1.57      matthew   756: my %ids_by_symb;
                    757: my %symbs_by_id;
                    758: 
                    759: sub get_symb_id {
                    760:     my ($symb) = @_;
1.61      matthew   761:     if (! $have_read_symb_table) {
                    762:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    763:         foreach (@Result) {
                    764:             $ids_by_symb{$_->[1]}=$_->[0];
                    765:         }
                    766:         $have_read_symb_table = 1;
                    767:     }
1.57      matthew   768:     if (! exists($ids_by_symb{$symb})) {
                    769:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
                    770:         undef(%ids_by_symb);
                    771:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    772:         foreach (@Result) {
                    773:             $ids_by_symb{$_->[1]}=$_->[0];
                    774:         }
                    775:     }
                    776:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
                    777:     return undef; # error
                    778: }
                    779: 
                    780: sub get_symb {
                    781:     my ($symb_id) = @_;
                    782:     if (! exists($symbs_by_id{$symb_id})  || 
                    783:         ! defined($symbs_by_id{$symb_id}) ||
                    784:         $symbs_by_id{$symb_id} eq '') {
                    785:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    786:         foreach (@Result) {
                    787:             $symbs_by_id{$_->[0]}=$_->[1];
                    788:         }
                    789:     }
                    790:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
                    791:     return undef; # error
                    792: }
                    793: 
                    794: ################################################
                    795: ################################################
                    796: 
                    797: =pod
                    798: 
                    799: =item &get_student_id()
                    800: 
                    801: Get the MySQL id of a student.
                    802: 
                    803: Input: $sname, $dom
                    804: 
                    805: Output: undef on error, integer $student_id on success.
                    806: 
                    807: =item &get_student()
                    808: 
                    809: Get student username:domain associated with the MySQL student_id.
                    810: 
                    811: Input: $student_id
                    812: 
                    813: Output: undef on error, string $student (username:domain) on success.
                    814: 
                    815: =cut
                    816: 
                    817: ################################################
                    818: ################################################
                    819: 
1.61      matthew   820: my $have_read_student_table = 0;
1.57      matthew   821: my %ids_by_student;
                    822: my %students_by_id;
                    823: 
                    824: sub get_student_id {
                    825:     my ($sname,$sdom) = @_;
                    826:     my $student = $sname.':'.$sdom;
1.61      matthew   827:     if (! $have_read_student_table) {
                    828:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    829:         foreach (@Result) {
                    830:             $ids_by_student{$_->[1]}=$_->[0];
                    831:         }
                    832:         $have_read_student_table = 1;
                    833:     }
1.57      matthew   834:     if (! exists($ids_by_student{$student})) {
1.113     matthew   835:         &populate_student_table();
1.57      matthew   836:         undef(%ids_by_student);
1.113     matthew   837:         undef(%students_by_id);
1.57      matthew   838:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    839:         foreach (@Result) {
                    840:             $ids_by_student{$_->[1]}=$_->[0];
                    841:         }
                    842:     }
                    843:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
                    844:     return undef; # error
                    845: }
                    846: 
                    847: sub get_student {
                    848:     my ($student_id) = @_;
                    849:     if (! exists($students_by_id{$student_id})  || 
                    850:         ! defined($students_by_id{$student_id}) ||
                    851:         $students_by_id{$student_id} eq '') {
                    852:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    853:         foreach (@Result) {
                    854:             $students_by_id{$_->[0]}=$_->[1];
                    855:         }
                    856:     }
                    857:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
                    858:     return undef; # error
                    859: }
1.99      matthew   860: 
1.113     matthew   861: sub populate_student_table {
                    862:     my ($courseid) = @_;
                    863:     if (! defined($courseid)) {
1.146     albertel  864:         $courseid = $env{'request.course.id'};
1.113     matthew   865:     }
                    866:     #
                    867:     &setup_table_names($courseid);
1.134     matthew   868:     &init_dbs($courseid,0);
1.113     matthew   869:     my $dbh = &Apache::lonmysql::get_dbh();
                    870:     my $request = 'INSERT IGNORE INTO '.$student_table.
                    871:         "(student,section,status) VALUES ";
1.150     albertel  872:     my $cdom = $env{'course.'.$courseid.'.domain'};
                    873:     my $cnum = $env{'course.'.$courseid.'.num'};
                    874:     my $classlist = &get_classlist($cdom,$cnum);
1.113     matthew   875:     my $student_count=0;
                    876:     while (my ($student,$data) = each %$classlist) {
                    877:         my ($section,$status) = ($data->[&CL_SECTION()],
                    878:                                  $data->[&CL_STATUS()]);
                    879:         if ($section eq '' || $section =~ /^\s*$/) {
                    880:             $section = 'none';
                    881:         }
                    882:         $request .= "('".$student."','".$section."','".$status."'),";
                    883:         $student_count++;
                    884:     }
                    885:     return if ($student_count == 0);
                    886:     chop($request);
                    887:     $dbh->do($request);
                    888:     if ($dbh->err()) {
                    889:         &Apache::lonnet::logthis("error ".$dbh->errstr().
                    890:                                  " occured executing \n".
                    891:                                  $request);
                    892:     }
                    893:     return;
                    894: }
                    895: 
1.99      matthew   896: ################################################
                    897: ################################################
                    898: 
                    899: =pod
                    900: 
                    901: =item &clear_internal_caches()
                    902: 
                    903: Causes the internal caches used in get_student_id, get_student,
                    904: get_symb_id, get_symb, get_part_id, and get_part to be undef'd.
                    905: 
                    906: Needs to be called before the first operation with the MySQL database
                    907: for a given Apache request.
                    908: 
                    909: =cut
                    910: 
                    911: ################################################
                    912: ################################################
                    913: sub clear_internal_caches {
                    914:     $have_read_part_table = 0;
                    915:     undef(%ids_by_part);
                    916:     undef(%parts_by_id);
                    917:     $have_read_symb_table = 0;
                    918:     undef(%ids_by_symb);
                    919:     undef(%symbs_by_id);
                    920:     $have_read_student_table = 0;
                    921:     undef(%ids_by_student);
                    922:     undef(%students_by_id);
                    923: }
                    924: 
1.57      matthew   925: ################################################
                    926: ################################################
                    927: 
                    928: =pod
                    929: 
1.89      matthew   930: =item &update_full_student_data($sname,$sdom,$courseid)
                    931: 
                    932: Does a lonnet::dump on a student to populate the courses tables.
                    933: 
                    934: Input: $sname, $sdom, $courseid
                    935: 
                    936: Output: $returnstatus
                    937: 
                    938: $returnstatus is a string describing any errors that occured.  'okay' is the
                    939: default.
                    940: 
                    941: This subroutine loads a students data using lonnet::dump and inserts
                    942: it into the MySQL database.  The inserts are done on three tables, 
                    943: $fulldump_response_table, $fulldump_part_table, and $fulldump_timestamp_table.
                    944: The INSERT calls are made directly by this subroutine, not through lonmysql 
                    945: because we do a 'bulk'insert which takes advantage of MySQLs non-SQL 
                    946: compliant INSERT command to insert multiple rows at a time.  
                    947: If anything has gone wrong during this process, $returnstatus is updated with 
                    948: a description of the error.
                    949: 
                    950: Once the "fulldump" tables are updated, the tables used for chart and
                    951: spreadsheet (which hold only the current state of the student on their
                    952: homework, not historical data) are updated.  If all updates have occured 
1.113     matthew   953: successfully, $student_table is updated to reflect the time of the update.
1.89      matthew   954: 
                    955: Notice we do not insert the data and immediately query it.  This means it
                    956: is possible for there to be data returned this first time that is not 
                    957: available the second time.  CYA.
                    958: 
                    959: =cut
                    960: 
                    961: ################################################
                    962: ################################################
                    963: sub update_full_student_data {
                    964:     my ($sname,$sdom,$courseid) = @_;
                    965:     #
                    966:     # Set up database names
                    967:     &setup_table_names($courseid);
                    968:     #
                    969:     my $student_id = &get_student_id($sname,$sdom);
                    970:     my $student = $sname.':'.$sdom;
                    971:     #
                    972:     my $returnstatus = 'okay';
                    973:     #
                    974:     # Download students data
                    975:     my $time_of_retrieval = time;
                    976:     my @tmp = &Apache::lonnet::dump($courseid,$sdom,$sname);
                    977:     if (@tmp && $tmp[0] =~ /^error/) {
                    978:         $returnstatus = 'error retrieving full student data';
                    979:         return $returnstatus;
                    980:     } elsif (! @tmp) {
                    981:         $returnstatus = 'okay: no student data';
                    982:         return $returnstatus;
                    983:     }
                    984:     my %studentdata = @tmp;
                    985:     #
                    986:     # Get database handle and clean out the tables 
                    987:     my $dbh = &Apache::lonmysql::get_dbh();
                    988:     $dbh->do('DELETE FROM '.$fulldump_response_table.' WHERE student_id='.
                    989:              $student_id);
                    990:     $dbh->do('DELETE FROM '.$fulldump_part_table.' WHERE student_id='.
                    991:              $student_id);
                    992:     $dbh->do('DELETE FROM '.$fulldump_timestamp_table.' WHERE student_id='.
                    993:              $student_id);
                    994:     #
                    995:     # Parse and store the data into a form we can handle
                    996:     my $partdata;
                    997:     my $respdata;
                    998:     while (my ($key,$value) = each(%studentdata)) {
                    999:         next if ($key =~ /^(\d+):(resource$|subnum$|keys:)/);
                   1000:         my ($transaction,$symb,$parameter) = split(':',$key);
                   1001:         my $symb_id = &get_symb_id($symb);
                   1002:         if ($parameter eq 'timestamp') {
                   1003:             # We can deal with 'timestamp' right away
                   1004:             my @timestamp_storage = ($symb_id,$student_id,
                   1005:                                      $transaction,$value);
1.98      matthew  1006:             my $store_command = 'INSERT IGNORE INTO '.$fulldump_timestamp_table.
1.89      matthew  1007:                 " VALUES ('".join("','",@timestamp_storage)."');";
                   1008:             $dbh->do($store_command);
                   1009:             if ($dbh->err()) {
                   1010:                 &Apache::lonnet::logthis('unable to execute '.$store_command);
                   1011:                 &Apache::lonnet::logthis($dbh->errstr());
                   1012:             }
                   1013:             next;
                   1014:         } elsif ($parameter eq 'version') {
                   1015:             next;
1.90      matthew  1016:         } elsif ($parameter =~ /^resource\.(.*)\.(tries|
                   1017:                                                   award|
                   1018:                                                   awarded|
                   1019:                                                   previous|
                   1020:                                                   solved|
                   1021:                                                   awarddetail|
                   1022:                                                   submission|
                   1023:                                                   submissiongrading|
                   1024:                                                   molecule)\s*$/x){
1.89      matthew  1025:             # we do not have enough information to store an 
                   1026:             # entire row, so we save it up until later.
                   1027:             my ($part_and_resp_id,$field) = ($1,$2);
                   1028:             my ($part,$part_id,$resp,$resp_id);
                   1029:             if ($part_and_resp_id =~ /\./) {
                   1030:                 ($part,$resp) = split(/\./,$part_and_resp_id);
                   1031:                 $part_id = &get_part_id($part);
                   1032:                 $resp_id = &get_part_id($resp);
                   1033:             } else {
                   1034:                 $part_id = &get_part_id($part_and_resp_id);
                   1035:             }
1.90      matthew  1036:             # Deal with part specific data
1.89      matthew  1037:             if ($field =~ /^(tries|award|awarded|previous)$/) {
                   1038:                 $partdata->{$symb_id}->{$part_id}->{$transaction}->{$field}=$value;
                   1039:             }
1.90      matthew  1040:             # deal with response specific data
1.89      matthew  1041:             if (defined($resp_id) &&
1.100     matthew  1042:                 $field =~ /^(awarddetail|
1.90      matthew  1043:                              submission|
                   1044:                              submissiongrading|
                   1045:                              molecule)$/x) {
1.89      matthew  1046:                 if ($field eq 'submission') {
                   1047:                     # We have to be careful with user supplied input.
                   1048:                     # most of the time we are okay because it is escaped.
                   1049:                     # However, there is one wrinkle: submissions which end in
                   1050:                     # and odd number of '\' cause insert errors to occur.  
                   1051:                     # Best trap this somehow...
1.116     matthew  1052:                     $value = $dbh->quote($value);
1.89      matthew  1053:                 }
1.90      matthew  1054:                 if ($field eq 'submissiongrading' || 
                   1055:                     $field eq 'molecule') {
                   1056:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific'}=$field;
                   1057:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific_value'}=$value;
                   1058:                 } else {
                   1059:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{$field}=$value;
                   1060:                 }
1.89      matthew  1061:             }
                   1062:         }
                   1063:     }
                   1064:     ##
                   1065:     ## Store the part data
1.98      matthew  1066:     my $store_command = 'INSERT IGNORE INTO '.$fulldump_part_table.
1.89      matthew  1067:         ' VALUES '."\n";
                   1068:     my $store_rows = 0;
                   1069:     while (my ($symb_id,$hash1) = each (%$partdata)) {
                   1070:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1071:             while (my ($transaction,$data) = each (%$hash2)) {
                   1072:                 $store_command .= "('".join("','",$symb_id,$part_id,
                   1073:                                             $student_id,
                   1074:                                             $transaction,
1.101     matthew  1075:                                             $data->{'tries'},
1.89      matthew  1076:                                             $data->{'award'},
                   1077:                                             $data->{'awarded'},
                   1078:                                             $data->{'previous'})."'),";
                   1079:                 $store_rows++;
                   1080:             }
                   1081:         }
                   1082:     }
                   1083:     if ($store_rows) {
                   1084:         chop($store_command);
                   1085:         $dbh->do($store_command);
                   1086:         if ($dbh->err) {
                   1087:             $returnstatus = 'error storing part data';
                   1088:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1089:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1090:         }
                   1091:     }
                   1092:     ##
                   1093:     ## Store the response data
1.98      matthew  1094:     $store_command = 'INSERT IGNORE INTO '.$fulldump_response_table.
1.89      matthew  1095:         ' VALUES '."\n";
                   1096:     $store_rows = 0;
                   1097:     while (my ($symb_id,$hash1) = each (%$respdata)) {
                   1098:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1099:             while (my ($resp_id,$hash3) = each (%$hash2)) {
                   1100:                 while (my ($transaction,$data) = each (%$hash3)) {
1.112     matthew  1101:                     my $submission = $data->{'submission'};
                   1102:                     # We have to be careful with user supplied input.
                   1103:                     # most of the time we are okay because it is escaped.
                   1104:                     # However, there is one wrinkle: submissions which end in
                   1105:                     # and odd number of '\' cause insert errors to occur.  
                   1106:                     # Best trap this somehow...
                   1107:                     $submission = $dbh->quote($submission);
                   1108:                     $store_command .= "('".
                   1109:                         join("','",$symb_id,$part_id,
                   1110:                              $resp_id,$student_id,
                   1111:                              $transaction,
                   1112:                              $data->{'awarddetail'},
                   1113:                              $data->{'response_specific'},
                   1114:                              $data->{'response_specific_value'}).
                   1115:                              "',".$submission."),";
1.89      matthew  1116:                     $store_rows++;
                   1117:                 }
                   1118:             }
                   1119:         }
                   1120:     }
                   1121:     if ($store_rows) {
                   1122:         chop($store_command);
                   1123:         $dbh->do($store_command);
                   1124:         if ($dbh->err) {
                   1125:             $returnstatus = 'error storing response data';
                   1126:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1127:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1128:         }
                   1129:     }
                   1130:     ##
                   1131:     ## Update the students "current" data in the performance 
                   1132:     ## and parameters tables.
                   1133:     my ($status,undef) = &store_student_data
                   1134:         ($sname,$sdom,$courseid,
                   1135:          &Apache::lonnet::convert_dump_to_currentdump(\%studentdata));
                   1136:     if ($returnstatus eq 'okay' && $status ne 'okay') {
                   1137:         $returnstatus = 'error storing current data:'.$status;
                   1138:     } elsif ($status ne 'okay') {
                   1139:         $returnstatus .= ' error storing current data:'.$status;
                   1140:     }        
                   1141:     ##
                   1142:     ## Update the students time......
                   1143:     if ($returnstatus eq 'okay') {
1.113     matthew  1144:         &store_updatetime($student_id,$time_of_retrieval,$time_of_retrieval);
                   1145:         if ($dbh->err) {
                   1146:             if ($returnstatus eq 'okay') {
                   1147:                 $returnstatus = 'error updating student time';
                   1148:             } else {
                   1149:                 $returnstatus = 'error updating student time';
                   1150:             }
                   1151:         }
1.89      matthew  1152:     }
                   1153:     return $returnstatus;
                   1154: }
                   1155: 
                   1156: ################################################
                   1157: ################################################
                   1158: 
                   1159: =pod
                   1160: 
1.57      matthew  1161: =item &update_student_data()
                   1162: 
                   1163: Input: $sname, $sdom, $courseid
                   1164: 
                   1165: Output: $returnstatus, \%student_data
                   1166: 
                   1167: $returnstatus is a string describing any errors that occured.  'okay' is the
                   1168: default.
                   1169: \%student_data is the data returned by a call to lonnet::currentdump.
                   1170: 
                   1171: This subroutine loads a students data using lonnet::currentdump and inserts
                   1172: it into the MySQL database.  The inserts are done on two tables, 
                   1173: $performance_table and $parameters_table.  $parameters_table holds the data 
                   1174: that is not included in $performance_table.  See the description of 
                   1175: $performance_table elsewhere in this file.  The INSERT calls are made
                   1176: directly by this subroutine, not through lonmysql because we do a 'bulk'
                   1177: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
                   1178: insert multiple rows at a time.  If anything has gone wrong during this
                   1179: process, $returnstatus is updated with a description of the error and
                   1180: \%student_data is returned.  
                   1181: 
                   1182: Notice we do not insert the data and immediately query it.  This means it
                   1183: is possible for there to be data returned this first time that is not 
                   1184: available the second time.  CYA.
                   1185: 
                   1186: =cut
                   1187: 
                   1188: ################################################
                   1189: ################################################
                   1190: sub update_student_data {
                   1191:     my ($sname,$sdom,$courseid) = @_;
                   1192:     #
1.60      matthew  1193:     # Set up database names
                   1194:     &setup_table_names($courseid);
                   1195:     #
1.57      matthew  1196:     my $student_id = &get_student_id($sname,$sdom);
                   1197:     my $student = $sname.':'.$sdom;
                   1198:     #
                   1199:     my $returnstatus = 'okay';
                   1200:     #
                   1201:     # Download students data
                   1202:     my $time_of_retrieval = time;
                   1203:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
                   1204:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
                   1205:         &Apache::lonnet::logthis('error getting data for '.
                   1206:                                  $sname.':'.$sdom.' in course '.$courseid.
                   1207:                                  ':'.$tmp[0]);
                   1208:         $returnstatus = 'error getting data';
1.79      matthew  1209:         return ($returnstatus,undef);
1.57      matthew  1210:     }
                   1211:     if (scalar(@tmp) < 1) {
                   1212:         return ('no data',undef);
                   1213:     }
                   1214:     my %student_data = @tmp;
1.89      matthew  1215:     my @Results = &store_student_data($sname,$sdom,$courseid,\%student_data);
                   1216:     #
                   1217:     # Set the students update time
1.96      matthew  1218:     if ($Results[0] eq 'okay') {
1.148     matthew  1219:         &store_updatetime($student_id,$time_of_retrieval);
1.95      matthew  1220:     }
1.89      matthew  1221:     #
                   1222:     return @Results;
                   1223: }
                   1224: 
1.113     matthew  1225: sub store_updatetime {
                   1226:     my ($student_id,$updatetime,$fullupdatetime)=@_;
                   1227:     my $values = '';
                   1228:     if (defined($updatetime)) {
                   1229:         $values = 'updatetime='.$updatetime.' ';
                   1230:     }
                   1231:     if (defined($fullupdatetime)) {
                   1232:         if ($values ne '') {
                   1233:             $values .= ',';
                   1234:         }
                   1235:         $values .= 'fullupdatetime='.$fullupdatetime.' ';
                   1236:     }
                   1237:     return if ($values eq '');
                   1238:     my $dbh = &Apache::lonmysql::get_dbh();
                   1239:     my $request = 'UPDATE '.$student_table.' SET '.$values.
                   1240:         ' WHERE student_id='.$student_id.' LIMIT 1';
                   1241:     $dbh->do($request);
                   1242: }
                   1243: 
1.89      matthew  1244: sub store_student_data {
                   1245:     my ($sname,$sdom,$courseid,$student_data) = @_;
                   1246:     #
                   1247:     my $student_id = &get_student_id($sname,$sdom);
                   1248:     my $student = $sname.':'.$sdom;
                   1249:     #
                   1250:     my $returnstatus = 'okay';
1.57      matthew  1251:     #
                   1252:     # Remove all of the students data from the table
1.60      matthew  1253:     my $dbh = &Apache::lonmysql::get_dbh();
                   1254:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
                   1255:              $student_id);
                   1256:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
                   1257:              $student_id);
1.57      matthew  1258:     #
                   1259:     # Store away the data
                   1260:     #
                   1261:     my $starttime = Time::HiRes::time;
                   1262:     my $elapsed = 0;
                   1263:     my $rows_stored;
1.98      matthew  1264:     my $store_parameters_command  = 'INSERT IGNORE INTO '.$parameters_table.
1.60      matthew  1265:         ' VALUES '."\n";
1.61      matthew  1266:     my $num_parameters = 0;
1.98      matthew  1267:     my $store_performance_command = 'INSERT IGNORE INTO '.$performance_table.
1.60      matthew  1268:         ' VALUES '."\n";
1.79      matthew  1269:     return ('error',undef) if (! defined($dbh));
1.89      matthew  1270:     while (my ($current_symb,$param_hash) = each(%{$student_data})) {
1.57      matthew  1271:         #
                   1272:         # make sure the symb is set up properly
                   1273:         my $symb_id = &get_symb_id($current_symb);
                   1274:         #
1.147     matthew  1275:         # Parameters
1.63      matthew  1276:         while (my ($parameter,$value) = each(%$param_hash)) {
                   1277:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
1.147     matthew  1278:                 my $sql_parameter = "('".join("','",
                   1279:                                               $symb_id,$student_id,
                   1280:                                               $parameter)."',".
                   1281:                                                   $dbh->quote($value)."),\n";
1.61      matthew  1282:                 $num_parameters ++;
1.147     matthew  1283:                 if ($sql_parameter !~ /''/) {
                   1284:                     $store_parameters_command .= $sql_parameter;
1.149     albertel 1285:                     #$rows_stored++;
1.57      matthew  1286:                 }
                   1287:             }
1.147     matthew  1288:         }
                   1289:         # Performance
                   1290:         my %stored;
                   1291:         while (my ($parameter,$value) = each(%$param_hash)) {
                   1292:             next if ($parameter !~ /^resource\.(.*)\.(solved|awarded)$/);
                   1293:             my $part = $1;
1.151     albertel 1294: 	    next if ($part =~ /\./);
1.147     matthew  1295:             next if (exists($stored{$part}));
                   1296:             $stored{$part}++;
1.57      matthew  1297:             #
                   1298:             my $part_id = &get_part_id($part);
                   1299:             next if (!defined($part_id));
                   1300:             my $solved  = $value;
                   1301:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
                   1302:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
                   1303:             my $award   = $param_hash->{'resource.'.$part.'.award'};
                   1304:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
                   1305:             my $timestamp = $param_hash->{'timestamp'};
1.60      matthew  1306:             #
1.74      matthew  1307:             $solved      = '' if (! defined($solved));
1.57      matthew  1308:             $tries       = '' if (! defined($tries));
                   1309:             $awarded     = '' if (! defined($awarded));
                   1310:             $award       = '' if (! defined($award));
                   1311:             $awarddetail = '' if (! defined($awarddetail));
1.147     matthew  1312:             my $sql_performance = 
                   1313:                 "('".join("','",$symb_id,$student_id,$part_id,$part,
                   1314:                                 $solved,$tries,$awarded,$award,
                   1315:                                 $awarddetail,$timestamp)."'),\n";
                   1316:             $store_performance_command .= $sql_performance;
1.57      matthew  1317:             $rows_stored++;
                   1318:         }
                   1319:     }
1.149     albertel 1320:     if (! $rows_stored) { return ($returnstatus, undef); }
1.147     matthew  1321:     $store_parameters_command =~ s|,\n$||;
                   1322:     $store_performance_command =~ s|,\n$||;
1.57      matthew  1323:     my $start = Time::HiRes::time;
1.94      matthew  1324:     $dbh->do($store_performance_command);
                   1325:     if ($dbh->err()) {
1.147     matthew  1326:         &Apache::lonnet::logthis('performance bigass insert error:'.
                   1327:                                  $dbh->errstr());
                   1328:         &Apache::lonnet::logthis('command = '.$/.$store_performance_command);
1.94      matthew  1329:         $returnstatus = 'error: unable to insert performance into database';
                   1330:         return ($returnstatus,$student_data);
                   1331:     }
1.61      matthew  1332:     $dbh->do($store_parameters_command) if ($num_parameters>0);
1.57      matthew  1333:     if ($dbh->err()) {
1.147     matthew  1334:         &Apache::lonnet::logthis('parameters bigass insert error:'.
                   1335:                                  $dbh->errstr());
                   1336:         &Apache::lonnet::logthis('command = '.$/.$store_parameters_command);
1.87      matthew  1337:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
                   1338:         &Apache::lonnet::logthis('student_id = '.$student_id);
1.57      matthew  1339:         $returnstatus = 'error: unable to insert parameters into database';
1.89      matthew  1340:         return ($returnstatus,$student_data);
1.57      matthew  1341:     }
                   1342:     $elapsed += Time::HiRes::time - $start;
1.89      matthew  1343:     return ($returnstatus,$student_data);
1.57      matthew  1344: }
                   1345: 
1.89      matthew  1346: ######################################
                   1347: ######################################
1.57      matthew  1348: 
                   1349: =pod
                   1350: 
1.89      matthew  1351: =item &ensure_tables_are_set_up($courseid)
1.57      matthew  1352: 
1.89      matthew  1353: Checks to be sure the MySQL tables for the given class are set up.
                   1354: If $courseid is omitted it will be obtained from the environment.
1.57      matthew  1355: 
1.89      matthew  1356: Returns nothing on success and 'error' on failure
1.57      matthew  1357: 
                   1358: =cut
                   1359: 
1.89      matthew  1360: ######################################
                   1361: ######################################
                   1362: sub ensure_tables_are_set_up {
                   1363:     my ($courseid) = @_;
1.146     albertel 1364:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.61      matthew  1365:     # 
                   1366:     # Clean out package variables
1.57      matthew  1367:     &setup_table_names($courseid);
                   1368:     #
                   1369:     # if the tables do not exist, make them
                   1370:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
1.113     matthew  1371:     my ($found_symb,$found_student,$found_part,
1.89      matthew  1372:         $found_performance,$found_parameters,$found_fulldump_part,
1.127     matthew  1373:         $found_fulldump_response,$found_fulldump_timestamp,
                   1374:         $found_weight);
1.57      matthew  1375:     foreach (@CurrentTable) {
                   1376:         $found_symb        = 1 if ($_ eq $symb_table);
                   1377:         $found_student     = 1 if ($_ eq $student_table);
                   1378:         $found_part        = 1 if ($_ eq $part_table);
                   1379:         $found_performance = 1 if ($_ eq $performance_table);
                   1380:         $found_parameters  = 1 if ($_ eq $parameters_table);
1.89      matthew  1381:         $found_fulldump_part      = 1 if ($_ eq $fulldump_part_table);
                   1382:         $found_fulldump_response  = 1 if ($_ eq $fulldump_response_table);
                   1383:         $found_fulldump_timestamp = 1 if ($_ eq $fulldump_timestamp_table);
1.127     matthew  1384:         $found_weight      = 1 if ($_ eq $weight_table);
1.57      matthew  1385:     }
1.127     matthew  1386:     if (!$found_symb          || 
                   1387:         !$found_student       || !$found_part              ||
                   1388:         !$found_performance   || !$found_parameters        ||
1.89      matthew  1389:         !$found_fulldump_part || !$found_fulldump_response ||
1.127     matthew  1390:         !$found_fulldump_timestamp || !$found_weight ) {
1.134     matthew  1391:         if (&init_dbs($courseid,1)) {
1.89      matthew  1392:             return 'error';
1.57      matthew  1393:         }
                   1394:     }
1.89      matthew  1395: }
                   1396: 
                   1397: ################################################
                   1398: ################################################
                   1399: 
                   1400: =pod
                   1401: 
                   1402: =item &ensure_current_data()
                   1403: 
                   1404: Input: $sname, $sdom, $courseid
                   1405: 
                   1406: Output: $status, $data
                   1407: 
                   1408: This routine ensures the data for a given student is up to date.
1.113     matthew  1409: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1410: If the students data is out of date, &update_student_data() is called.  
                   1411: The return values from the call to &update_student_data() are returned.
                   1412: 
                   1413: =cut
                   1414: 
                   1415: ################################################
                   1416: ################################################
                   1417: sub ensure_current_data {
                   1418:     my ($sname,$sdom,$courseid) = @_;
                   1419:     my $status = 'okay';   # return value
                   1420:     #
1.146     albertel 1421:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.89      matthew  1422:     &ensure_tables_are_set_up($courseid);
1.57      matthew  1423:     #
                   1424:     # Get the update time for the user
                   1425:     my $updatetime = 0;
1.60      matthew  1426:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1427:         ($sdom,$sname,$courseid.'.db',
                   1428:          $Apache::lonnet::perlvar{'lonUsersDir'});
1.57      matthew  1429:     #
1.87      matthew  1430:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1431:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.87      matthew  1432:                                              "student_id ='$student_id'");
1.57      matthew  1433:     my $data = undef;
                   1434:     if (@Result) {
1.113     matthew  1435:         $updatetime = $Result[0]->[5];  # Ack!  This is dumb!
1.57      matthew  1436:     }
                   1437:     if ($modifiedtime > $updatetime) {
                   1438:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
                   1439:     }
                   1440:     return ($status,$data);
                   1441: }
                   1442: 
                   1443: ################################################
                   1444: ################################################
                   1445: 
                   1446: =pod
                   1447: 
1.89      matthew  1448: =item &ensure_current_full_data($sname,$sdom,$courseid)
                   1449: 
                   1450: Input: $sname, $sdom, $courseid
                   1451: 
                   1452: Output: $status
                   1453: 
                   1454: This routine ensures the fulldata (the data from a lonnet::dump, not a
                   1455: lonnet::currentdump) for a given student is up to date.
1.113     matthew  1456: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1457: If the students fulldata is out of date, &update_full_student_data() is
                   1458: called.  
                   1459: 
                   1460: The return value from the call to &update_full_student_data() is returned.
                   1461: 
                   1462: =cut
                   1463: 
                   1464: ################################################
                   1465: ################################################
                   1466: sub ensure_current_full_data {
                   1467:     my ($sname,$sdom,$courseid) = @_;
                   1468:     my $status = 'okay';   # return value
                   1469:     #
1.146     albertel 1470:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.89      matthew  1471:     &ensure_tables_are_set_up($courseid);
                   1472:     #
                   1473:     # Get the update time for the user
                   1474:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1475:         ($sdom,$sname,$courseid.'.db',
                   1476:          $Apache::lonnet::perlvar{'lonUsersDir'});
                   1477:     #
                   1478:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1479:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.89      matthew  1480:                                              "student_id ='$student_id'");
                   1481:     my $updatetime;
                   1482:     if (@Result && ref($Result[0]) eq 'ARRAY') {
1.113     matthew  1483:         $updatetime = $Result[0]->[6];
1.89      matthew  1484:     }
                   1485:     if (! defined($updatetime) || $modifiedtime > $updatetime) {
                   1486:         $status = &update_full_student_data($sname,$sdom,$courseid);
                   1487:     }
                   1488:     return $status;
                   1489: }
                   1490: 
                   1491: ################################################
                   1492: ################################################
                   1493: 
                   1494: =pod
                   1495: 
1.57      matthew  1496: =item &get_student_data_from_performance_cache()
                   1497: 
                   1498: Input: $sname, $sdom, $symb, $courseid
                   1499: 
                   1500: Output: hash reference containing the data for the given student.
                   1501: If $symb is undef, all the students data is returned.
                   1502: 
                   1503: This routine is the heart of the local caching system.  See the description
                   1504: of $performance_table, $symb_table, $student_table, and $part_table.  The
                   1505: main task is building the MySQL request.  The tables appear in the request
                   1506: in the order in which they should be parsed by MySQL.  When searching
                   1507: on a student the $student_table is used to locate the 'student_id'.  All
                   1508: rows in $performance_table which have a matching 'student_id' are returned,
                   1509: with data from $part_table and $symb_table which match the entries in
                   1510: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
                   1511: the $symb_table is processed first, with matching rows grabbed from 
                   1512: $performance_table and filled in from $part_table and $student_table in
                   1513: that order.  
                   1514: 
                   1515: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
                   1516: interesting, especially if you play with the order the tables are listed.  
                   1517: 
                   1518: =cut
                   1519: 
                   1520: ################################################
                   1521: ################################################
                   1522: sub get_student_data_from_performance_cache {
                   1523:     my ($sname,$sdom,$symb,$courseid)=@_;
                   1524:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
1.61      matthew  1525:     &setup_table_names($courseid);
1.57      matthew  1526:     #
                   1527:     # Return hash
                   1528:     my $studentdata;
                   1529:     #
                   1530:     my $dbh = &Apache::lonmysql::get_dbh();
                   1531:     my $request = "SELECT ".
1.73      matthew  1532:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
1.63      matthew  1533:             "a.timestamp ";
1.57      matthew  1534:     if (defined($student)) {
                   1535:         $request .= "FROM $student_table AS b ".
                   1536:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
1.73      matthew  1537: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
1.57      matthew  1538:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
                   1539:                 "WHERE student='$student'";
                   1540:         if (defined($symb) && $symb ne '') {
1.67      matthew  1541:             $request .= " AND d.symb=".$dbh->quote($symb);
1.57      matthew  1542:         }
                   1543:     } elsif (defined($symb) && $symb ne '') {
                   1544:         $request .= "FROM $symb_table as d ".
                   1545:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
1.73      matthew  1546: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
1.57      matthew  1547:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
                   1548:                 "WHERE symb='".$dbh->quote($symb)."'";
                   1549:     }
                   1550:     my $starttime = Time::HiRes::time;
                   1551:     my $rows_retrieved = 0;
                   1552:     my $sth = $dbh->prepare($request);
                   1553:     $sth->execute();
                   1554:     if ($sth->err()) {
                   1555:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1556:         &Apache::lonnet::logthis("\n".$request."\n");
                   1557:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1558:         return undef;
                   1559:     }
                   1560:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1561:         $rows_retrieved++;
1.63      matthew  1562:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
1.57      matthew  1563:             (@$row);
                   1564:         my $base = 'resource.'.$part;
                   1565:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
                   1566:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
                   1567:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
                   1568:         $studentdata->{$symb}->{$base.'.award'}   = $award;
                   1569:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
                   1570:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
1.67      matthew  1571:     }
1.97      matthew  1572:     ## Get misc parameters
                   1573:     $request = 'SELECT c.symb,a.parameter,a.value '.
                   1574:         "FROM $student_table AS b ".
                   1575:         "LEFT JOIN $parameters_table AS a ON b.student_id=a.student_id ".
                   1576:         "LEFT JOIN $symb_table AS c ON c.symb_id = a.symb_id ".
                   1577:         "WHERE student='$student'";
                   1578:     if (defined($symb) && $symb ne '') {
                   1579:         $request .= " AND c.symb=".$dbh->quote($symb);
                   1580:     }
                   1581:     $sth = $dbh->prepare($request);
                   1582:     $sth->execute();
                   1583:     if ($sth->err()) {
                   1584:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1585:         &Apache::lonnet::logthis("\n".$request."\n");
                   1586:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1587:         if (defined($symb) && $symb ne '') {
                   1588:             $studentdata = $studentdata->{$symb};
                   1589:         }
                   1590:         return $studentdata;
                   1591:     }
                   1592:     #
                   1593:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1594:         $rows_retrieved++;
                   1595:         my ($symb,$parameter,$value) = (@$row);
                   1596:         $studentdata->{$symb}->{$parameter}  = $value;
                   1597:     }
                   1598:     #
1.67      matthew  1599:     if (defined($symb) && $symb ne '') {
                   1600:         $studentdata = $studentdata->{$symb};
1.57      matthew  1601:     }
                   1602:     return $studentdata;
                   1603: }
                   1604: 
                   1605: ################################################
                   1606: ################################################
                   1607: 
                   1608: =pod
                   1609: 
                   1610: =item &get_current_state()
                   1611: 
                   1612: Input: $sname,$sdom,$symb,$courseid
                   1613: 
                   1614: Output: Described below
1.46      matthew  1615: 
1.47      matthew  1616: Retrieve the current status of a students performance.  $sname and
1.46      matthew  1617: $sdom are the only required parameters.  If $symb is undef the results
1.47      matthew  1618: of an &Apache::lonnet::currentdump() will be returned.  
1.46      matthew  1619: If $courseid is undef it will be retrieved from the environment.
                   1620: 
                   1621: The return structure is based on &Apache::lonnet::currentdump.  If
                   1622: $symb is unspecified, all the students data is returned in a hash of
                   1623: the form:
                   1624: ( 
                   1625:   symb1 => { param1 => value1, param2 => value2 ... },
                   1626:   symb2 => { param1 => value1, param2 => value2 ... },
                   1627: )
                   1628: 
                   1629: If $symb is specified, a hash of 
                   1630: (
                   1631:   param1 => value1, 
                   1632:   param2 => value2,
                   1633: )
                   1634: is returned.
                   1635: 
1.57      matthew  1636: If no data is found for $symb, or if the student has no performance data,
1.46      matthew  1637: an empty list is returned.
                   1638: 
                   1639: =cut
                   1640: 
                   1641: ################################################
                   1642: ################################################
                   1643: sub get_current_state {
1.47      matthew  1644:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
                   1645:     #
1.146     albertel 1646:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.47      matthew  1647:     #
1.61      matthew  1648:     return () if (! defined($sname) || ! defined($sdom));
                   1649:     #
1.57      matthew  1650:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
1.77      matthew  1651: #    &Apache::lonnet::logthis
                   1652: #        ('sname = '.$sname.
                   1653: #         ' domain = '.$sdom.
                   1654: #         ' status = '.$status.
                   1655: #         ' data is '.(defined($data)?'defined':'undefined'));
1.73      matthew  1656: #    while (my ($symb,$hash) = each(%$data)) {
                   1657: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
                   1658: #        while (my ($key,$value) = each (%$hash)) {
                   1659: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
                   1660: #        }
                   1661: #    }
1.47      matthew  1662:     #
1.79      matthew  1663:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
                   1664:         return %{$data->{$symb}};
                   1665:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
                   1666:         return %$data;
                   1667:     } 
                   1668:     if ($status eq 'no data') {
1.57      matthew  1669:         return ();
                   1670:     } else {
                   1671:         if ($status ne 'okay' && $status ne '') {
                   1672:             &Apache::lonnet::logthis('status = '.$status);
1.47      matthew  1673:             return ();
                   1674:         }
1.57      matthew  1675:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
                   1676:                                                       $symb,$courseid);
                   1677:         return %$returnhash if (defined($returnhash));
1.46      matthew  1678:     }
1.57      matthew  1679:     return ();
1.61      matthew  1680: }
                   1681: 
                   1682: ################################################
                   1683: ################################################
                   1684: 
                   1685: =pod
                   1686: 
                   1687: =item &get_problem_statistics()
                   1688: 
                   1689: Gather data on a given problem.  The database is assumed to be 
                   1690: populated and all local caching variables are assumed to be set
                   1691: properly.  This means you need to call &ensure_current_data for
                   1692: the students you are concerned with prior to calling this routine.
                   1693: 
1.124     matthew  1694: Inputs: $Sections, $status, $symb, $part, $courseid, $starttime, $endtime
1.61      matthew  1695: 
1.64      matthew  1696: =over 4
                   1697: 
1.124     matthew  1698: =item $Sections Array ref containing section names for students.  
                   1699: 'all' is allowed to be the first (and only) item in the array.
                   1700: 
                   1701: =item $status String describing the status of students
1.64      matthew  1702: 
                   1703: =item $symb is the symb for the problem.
                   1704: 
                   1705: =item $part is the part id you need statistics for
                   1706: 
                   1707: =item $courseid is the course id, of course!
                   1708: 
1.122     matthew  1709: =item $starttime and $endtime are unix times which to use to limit
                   1710: the statistical data.
                   1711: 
1.64      matthew  1712: =back
                   1713: 
1.66      matthew  1714: Outputs: See the code for up to date information.  A hash reference is
                   1715: returned.  The hash has the following keys defined:
1.64      matthew  1716: 
                   1717: =over 4
                   1718: 
1.66      matthew  1719: =item num_students The number of students attempting the problem
                   1720:       
                   1721: =item tries The total number of tries for the students
                   1722:       
                   1723: =item max_tries The maximum number of tries taken
                   1724:       
                   1725: =item mean_tries The average number of tries
                   1726:       
                   1727: =item num_solved The number of students able to solve the problem
                   1728:       
                   1729: =item num_override The number of students whose answer is 'correct_by_override'
                   1730:       
                   1731: =item deg_of_diff The degree of difficulty of the problem
                   1732:       
                   1733: =item std_tries The standard deviation of the number of tries
                   1734:       
                   1735: =item skew_tries The skew of the number of tries
1.64      matthew  1736: 
1.66      matthew  1737: =item per_wrong The number of students attempting the problem who were not
                   1738: able to answer it correctly.
1.64      matthew  1739: 
                   1740: =back
                   1741: 
1.61      matthew  1742: =cut
                   1743: 
                   1744: ################################################
                   1745: ################################################
                   1746: sub get_problem_statistics {
1.122     matthew  1747:     my ($Sections,$status,$symb,$part,$courseid,$starttime,$endtime) = @_;
1.61      matthew  1748:     return if (! defined($symb) || ! defined($part));
1.146     albertel 1749:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.61      matthew  1750:     #
1.100     matthew  1751:     &setup_table_names($courseid);
1.61      matthew  1752:     my $symb_id = &get_symb_id($symb);
                   1753:     my $part_id = &get_part_id($part);
                   1754:     my $stats_table = $courseid.'_problem_stats';
                   1755:     #
                   1756:     my $dbh = &Apache::lonmysql::get_dbh();
                   1757:     return undef if (! defined($dbh));
                   1758:     #
1.123     matthew  1759:     # Clean out the table
1.61      matthew  1760:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
                   1761:     my $request = 
1.115     matthew  1762:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   1763:         'SELECT a.student_id,a.solved,a.award,a.awarded,a.tries '.
                   1764:         'FROM '.$performance_table.' AS a ';
1.123     matthew  1765:     #
                   1766:     # See if we need to include some requirements on the students
1.115     matthew  1767:     if ((defined($Sections) && lc($Sections->[0]) ne 'all') || 
                   1768:         (defined($status)   && lc($status)        ne 'any')) {
                   1769:         $request .= 'NATURAL LEFT JOIN '.$student_table.' AS b ';
                   1770:     }
                   1771:     $request .= ' WHERE a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.123     matthew  1772:     #
                   1773:     # Limit the students included to those specified
1.115     matthew  1774:     if (defined($Sections) && lc($Sections->[0]) ne 'all') {
1.64      matthew  1775:         $request .= ' AND ('.
1.115     matthew  1776:             join(' OR ', map { "b.section='".$_."'" } @$Sections
1.64      matthew  1777:                  ).')';
                   1778:     }
1.115     matthew  1779:     if (defined($status) && lc($status) ne 'any') {
                   1780:         $request .= " AND b.status='".$status."'";
1.122     matthew  1781:     }
                   1782:     #
1.123     matthew  1783:     # Limit by starttime and endtime
1.122     matthew  1784:     my $time_requirements = undef;
                   1785:     if (defined($starttime)) {
                   1786:         $time_requirements .= 'a.timestamp>='.$starttime;
                   1787:         if (defined($endtime)) {
                   1788:             $time_requirements .= ' AND a.timestamp<='.$endtime;
                   1789:         }
                   1790:     } elsif (defined($endtime)) {
                   1791:         $time_requirements .= 'a.timestamp<='.$endtime;
                   1792:     }
                   1793:     if (defined($time_requirements)) {
                   1794:         $request .= ' AND '.$time_requirements;
1.115     matthew  1795:     }
1.123     matthew  1796:     #
                   1797:     # Finally, execute the request to create the temporary table
1.61      matthew  1798:     $dbh->do($request);
1.123     matthew  1799:     #
                   1800:     # Collect the first suite of statistics
1.128     matthew  1801:     $request = 'SELECT COUNT(*),SUM(tries),'.
                   1802:         'AVG(tries),STD(tries) '.
1.109     matthew  1803:         'FROM '.$stats_table;
1.128     matthew  1804:     my ($num,$tries,$mean,$STD) = &execute_SQL_request
1.109     matthew  1805:         ($dbh,$request);
1.128     matthew  1806:     #
                   1807:     $request = 'SELECT MAX(tries),MIN(tries) FROM '.$stats_table.
                   1808:         ' WHERE awarded>0';
                   1809:     if (defined($time_requirements)) {
                   1810:         $request .= ' AND '.$time_requirements;
                   1811:     }
                   1812:     my ($max,$min) = &execute_SQL_request($dbh,$request);
                   1813:     #
1.109     matthew  1814:     $request = 'SELECT SUM(awarded) FROM '.$stats_table;
1.128     matthew  1815:     if (defined($time_requirements)) {
                   1816:         $request .= ' AND '.$time_requirements;
                   1817:     }
1.109     matthew  1818:     my ($Solved) = &execute_SQL_request($dbh,$request);
1.128     matthew  1819:     #
1.109     matthew  1820:     $request = 'SELECT SUM(awarded) FROM '.$stats_table.
                   1821:         " WHERE solved='correct_by_override'";
1.128     matthew  1822:     if (defined($time_requirements)) {
                   1823:         $request .= ' AND '.$time_requirements;
                   1824:     }
1.109     matthew  1825:     my ($solved) = &execute_SQL_request($dbh,$request);
                   1826:     #
1.133     matthew  1827:     $Solved -= $solved;
                   1828:     #
1.61      matthew  1829:     $num    = 0 if (! defined($num));
                   1830:     $tries  = 0 if (! defined($tries));
1.128     matthew  1831:     $max    = 0 if (! defined($max));
                   1832:     $min    = 0 if (! defined($min));
1.61      matthew  1833:     $STD    = 0 if (! defined($STD));
1.133     matthew  1834:     $Solved = 0 if (! defined($Solved) || $Solved < 0);
1.61      matthew  1835:     $solved = 0 if (! defined($solved));
                   1836:     #
1.123     matthew  1837:     # Compute the more complicated statistics
1.61      matthew  1838:     my $DegOfDiff = 'nan';
1.66      matthew  1839:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
1.123     matthew  1840:     #
1.61      matthew  1841:     my $SKEW = 'nan';
1.66      matthew  1842:     my $wrongpercent = 0;
1.128     matthew  1843:     my $numwrong = 'nan';
1.61      matthew  1844:     if ($num > 0) {
                   1845:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
                   1846:                                      'POWER(tries - '.$STD.',3)'.
                   1847:                                      '))/'.$num.' FROM '.$stats_table);
1.128     matthew  1848:         $numwrong = $num-$Solved;
                   1849:         $wrongpercent=int(10*100*$numwrong/$num)/10;
1.61      matthew  1850:     }
                   1851:     #
1.123     matthew  1852:     # Drop the temporary table
                   1853:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
1.81      matthew  1854:     #
                   1855:     # Return result
1.66      matthew  1856:     return { num_students => $num,
                   1857:              tries        => $tries,
1.128     matthew  1858:              max_tries    => $max,
                   1859:              min_tries    => $min,
1.66      matthew  1860:              mean_tries   => $mean,
                   1861:              std_tries    => $STD,
                   1862:              skew_tries   => $SKEW,
                   1863:              num_solved   => $Solved,
                   1864:              num_override => $solved,
1.128     matthew  1865:              num_wrong    => $numwrong,
1.66      matthew  1866:              per_wrong    => $wrongpercent,
1.81      matthew  1867:              deg_of_diff  => $DegOfDiff };
1.61      matthew  1868: }
                   1869: 
1.127     matthew  1870: ##
                   1871: ## This is a helper for get_statistics
1.61      matthew  1872: sub execute_SQL_request {
                   1873:     my ($dbh,$request)=@_;
                   1874: #    &Apache::lonnet::logthis($request);
                   1875:     my $sth = $dbh->prepare($request);
1.153   ! albertel 1876:     if (!$sth) {
        !          1877: 	die($dbh->errstr . " SQL: $request");
        !          1878:     }
1.61      matthew  1879:     $sth->execute();
                   1880:     my $row = $sth->fetchrow_arrayref();
                   1881:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
                   1882:         return @$row;
                   1883:     }
                   1884:     return ();
                   1885: }
1.123     matthew  1886: 
1.127     matthew  1887: ######################################################
                   1888: ######################################################
                   1889: 
                   1890: =pod
                   1891: 
                   1892: =item &populate_weight_table
                   1893: 
                   1894: =cut
                   1895: 
                   1896: ######################################################
                   1897: ######################################################
                   1898: sub populate_weight_table {
                   1899:     my ($courseid) = @_;
                   1900:     if (! defined($courseid)) {
1.146     albertel 1901:         $courseid = $env{'request.course.id'};
1.127     matthew  1902:     }
                   1903:     #
                   1904:     &setup_table_names($courseid);
1.144     matthew  1905:     my $navmap = Apache::lonnavmaps::navmap->new();
                   1906:     if (!defined($navmap)) {
                   1907:         &Apache::lonnet::logthis('loncoursedata::populate_weight_table:'.$/.
                   1908:                                  '  unable to get navmaps resource'.$/.
                   1909:                                  '  '.join(' ',(caller)));
                   1910:         return;
                   1911:     }
                   1912:     my @sequences = $navmap->retrieveResources(undef,
                   1913:                                                sub { shift->is_map(); },1,0,1);
                   1914:     my @resources;
                   1915:     foreach my $seq (@sequences) {
                   1916:         push(@resources,$navmap->retrieveResources($seq,
                   1917:                                                    sub {shift->is_problem();},
                   1918:                                                    0,0,0));
                   1919:     }
                   1920:     if (! scalar(@resources)) {
                   1921:         &Apache::lonnet::logthis('loncoursedata::populate_weight_table:'.$/.
                   1922:                                  ' no resources returned for '.$courseid);
1.127     matthew  1923:         return;
                   1924:     }
                   1925:     #       Since we use lonnet::EXT to retrieve problem weights,
                   1926:     #       to ensure current data we must clear the caches out.
                   1927:     &Apache::lonnet::clear_EXT_cache_status();
                   1928:     my $dbh = &Apache::lonmysql::get_dbh();
                   1929:     my $request = 'INSERT IGNORE INTO '.$weight_table.
                   1930:         "(symb_id,part_id,weight) VALUES ";
                   1931:     my $weight;
1.144     matthew  1932:     foreach my $res (@resources) {
                   1933:         my $symb_id = &get_symb_id($res->symb);
                   1934:         foreach my $part (@{$res->parts}) {
1.127     matthew  1935:             my $part_id = &get_part_id($part);
                   1936:             $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
1.144     matthew  1937:                                            $res->symb,
1.127     matthew  1938:                                            undef,undef,undef);
                   1939:             if (!defined($weight) || ($weight eq '')) { 
                   1940:                 $weight=1;
                   1941:             }
                   1942:             $request .= "('".$symb_id."','".$part_id."','".$weight."'),";
                   1943:         }
                   1944:     }
                   1945:     $request =~ s/(,)$//;
                   1946: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   1947:     $dbh->do($request);
                   1948:     if ($dbh->err()) {
                   1949:         &Apache::lonnet::logthis("error ".$dbh->errstr().
                   1950:                                  " occured executing \n".
                   1951:                                  $request);
                   1952:     }
                   1953:     return;
                   1954: }
                   1955: 
                   1956: ##########################################################
                   1957: ##########################################################
1.61      matthew  1958: 
1.127     matthew  1959: =pod
                   1960: 
1.129     matthew  1961: =item &limit_by_start_end_times
                   1962: 
                   1963: Build SQL WHERE condition which limits the data collected by the start
                   1964: and end times provided
                   1965: 
                   1966: Inputs: $starttime, $endtime, $table
                   1967: 
                   1968: Returns: $time_limits
                   1969: 
                   1970: =cut
                   1971: 
                   1972: ##########################################################
                   1973: ##########################################################
                   1974: sub limit_by_start_end_time {
                   1975:     my ($starttime,$endtime,$table) = @_;
                   1976:     my $time_requirements = undef;
                   1977:     if (defined($starttime)) {
                   1978:         $time_requirements .= $table.".timestamp>='".$starttime."'";
                   1979:         if (defined($endtime)) {
                   1980:             $time_requirements .= " AND ".$table.".timestamp<='".$endtime."'";
                   1981:         }
                   1982:     } elsif (defined($endtime)) {
                   1983:         $time_requirements .= $table.".timestamp<='".$endtime."'";
                   1984:     }
                   1985:     return $time_requirements;
                   1986: }
                   1987: 
                   1988: ##########################################################
                   1989: ##########################################################
                   1990: 
                   1991: =pod
                   1992: 
1.127     matthew  1993: =item &limit_by_section_and_status
                   1994: 
                   1995: Build SQL WHERE condition which limits the data collected by section and
                   1996: student status.
                   1997: 
                   1998: Inputs: $Sections (array ref)
                   1999:     $enrollment (string: 'any', 'expired', 'active')
                   2000:     $tablename The name of the table that holds the student data
                   2001: 
                   2002: Returns: $student_requirements,$enrollment_requirements
                   2003: 
                   2004: =cut
                   2005: 
                   2006: ##########################################################
                   2007: ##########################################################
                   2008: sub limit_by_section_and_status {
                   2009:     my ($Sections,$enrollment,$tablename) = @_;
                   2010:     my $student_requirements = undef;
                   2011:     if ( (defined($Sections) && $Sections->[0] ne 'all')) {
                   2012:         $student_requirements = '('.
                   2013:             join(' OR ', map { $tablename.".section='".$_."'" } @$Sections
                   2014:                  ).')';
                   2015:     }
                   2016:     #
                   2017:     my $enrollment_requirements=undef;
                   2018:     if (defined($enrollment) && $enrollment ne 'Any') {
                   2019:         $enrollment_requirements = $tablename.".status='".$enrollment."'";
                   2020:     }
                   2021:     return ($student_requirements,$enrollment_requirements);
                   2022: }
                   2023: 
                   2024: ######################################################
                   2025: ######################################################
                   2026: 
                   2027: =pod
                   2028: 
                   2029: =item rank_students_by_scores_on_resources
                   2030: 
                   2031: Inputs: 
                   2032:     $resources: array ref of hash ref.  Each hash ref needs key 'symb'.
                   2033:     $Sections: array ref of sections to include,
                   2034:     $enrollment: string,
                   2035:     $courseid (may be omitted)
                   2036: 
                   2037: Returns; An array of arrays.  The sub arrays contain a student name and
                   2038: their score on the resources.
                   2039: 
                   2040: =cut
                   2041: 
                   2042: ######################################################
                   2043: ######################################################
                   2044: sub RNK_student { return 0; };
                   2045: sub RNK_score   { return 1; };
                   2046: 
                   2047: sub rank_students_by_scores_on_resources {
1.130     matthew  2048:     my ($resources,$Sections,$enrollment,$courseid,$starttime,$endtime) = @_;
1.127     matthew  2049:     return if (! defined($resources) || ! ref($resources) eq 'ARRAY');
                   2050:     if (! defined($courseid)) {
1.146     albertel 2051:         $courseid = $env{'request.course.id'};
1.127     matthew  2052:     }
                   2053:     #
                   2054:     &setup_table_names($courseid);
                   2055:     my $dbh = &Apache::lonmysql::get_dbh();
                   2056:     my ($section_limits,$enrollment_limits)=
                   2057:         &limit_by_section_and_status($Sections,$enrollment,'b');
                   2058:     my $symb_limits = '('.join(' OR ',map {'a.symb_id='.&get_symb_id($_);
                   2059:                                        } @$resources
                   2060:                                ).')';
1.130     matthew  2061:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
1.127     matthew  2062:     my $request = 'SELECT b.student,SUM(a.awarded*w.weight) AS score FROM '.
                   2063:         $performance_table.' AS a '.
                   2064:         'NATURAL LEFT JOIN '.$weight_table.' AS w '.
                   2065:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
                   2066:         'WHERE ';
                   2067:     if (defined($section_limits)) {
                   2068:         $request .= $section_limits.' AND ';
                   2069:     }
                   2070:     if (defined($enrollment_limits)) {
                   2071:         $request .= $enrollment_limits.' AND ';
                   2072:     }
1.130     matthew  2073:     if (defined($time_limits)) {
                   2074:         $request .= $time_limits.' AND ';
                   2075:     }
1.127     matthew  2076:     if ($symb_limits ne '()') {
                   2077:         $request .= $symb_limits.' AND ';
                   2078:     }
                   2079:     $request =~ s/( AND )$//;   # Remove extra conjunction
                   2080:     $request =~ s/( WHERE )$//; # In case there were no limits placed on it
                   2081:     $request .= ' GROUP BY a.student_id ORDER BY score';
                   2082:     #&Apache::lonnet::logthis('request = '.$/.$request);
                   2083:     my $sth = $dbh->prepare($request);
                   2084:     $sth->execute();
                   2085:     my $rows = $sth->fetchall_arrayref();
                   2086:     return ($rows);
                   2087: }
                   2088: 
                   2089: ########################################################
                   2090: ########################################################
                   2091: 
                   2092: =pod
                   2093: 
                   2094: =item &get_sum_of_scores
                   2095: 
                   2096: Inputs: $resource (hash ref, needs {'symb'} key),
                   2097: $part, (the part id),
                   2098: $students (array ref, contents of array are scalars holding 'sname:sdom'),
                   2099: $courseid
                   2100: 
                   2101: Returns: the sum of the score on the problem part over the students and the
                   2102:    maximum possible value for the sum (taken from the weight table).
                   2103: 
                   2104: =cut
                   2105: 
                   2106: ########################################################
                   2107: ########################################################
                   2108: sub get_sum_of_scores {
1.143     matthew  2109:     my ($symb,$part,$students,$courseid,$starttime,$endtime) = @_;
1.127     matthew  2110:     if (! defined($courseid)) {
1.146     albertel 2111:         $courseid = $env{'request.course.id'};
1.127     matthew  2112:     }
1.138     matthew  2113:     if (defined($students) && 
                   2114:         ((@$students == 0) ||
                   2115:          (@$students == 1 && (! defined($students->[0]) || 
                   2116:                               $students->[0] eq ''))
                   2117:          )
                   2118:         ){
                   2119:         undef($students);
                   2120:     }
1.127     matthew  2121:     #
                   2122:     &setup_table_names($courseid);
                   2123:     my $dbh = &Apache::lonmysql::get_dbh();
1.130     matthew  2124:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
1.127     matthew  2125:     my $request = 'SELECT SUM(a.awarded*w.weight),SUM(w.weight) FROM '.
                   2126:         $performance_table.' AS a '.
                   2127:         'NATURAL LEFT JOIN '.$weight_table.' AS w ';
1.143     matthew  2128:     $request .= 'WHERE a.symb_id='.&get_symb_id($symb).
1.127     matthew  2129:         ' AND a.part_id='.&get_part_id($part);
1.130     matthew  2130:     if (defined($time_limits)) {
                   2131:         $request .= ' AND '.$time_limits;
                   2132:     }
1.127     matthew  2133:     if (defined($students)) {
                   2134:         $request .= ' AND ('.
                   2135:             join(' OR ',map {'a.student_id='.&get_student_id(split(':',$_));
                   2136:                          } @$students).
                   2137:                              ')';
                   2138:     }
                   2139:     my $sth = $dbh->prepare($request);
                   2140:     $sth->execute();
                   2141:     my $rows = $sth->fetchrow_arrayref();
                   2142:     if ($dbh->err) {
1.138     matthew  2143:         &Apache::lonnet::logthis('error 1 = '.$dbh->errstr());
                   2144:         &Apache::lonnet::logthis('prepared then executed, fetchrow_arrayrefed'.
                   2145:                                  $/.$request);
1.127     matthew  2146:         return (undef,undef);
                   2147:     }
                   2148:     return ($rows->[0],$rows->[1]);
                   2149: }
                   2150: 
1.129     matthew  2151: ########################################################
                   2152: ########################################################
                   2153: 
                   2154: =pod
                   2155: 
                   2156: =item &score_stats
                   2157: 
                   2158: Inputs: $Sections, $enrollment, $symbs, $starttime,
                   2159:         $endtime, $courseid
                   2160: 
                   2161: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
                   2162: elsewhere in this module.  
                   2163: $symbs is an array ref of symbs
                   2164: 
                   2165: Returns: minimum, maximum, mean, s.d., number of students, and maximum
                   2166:   possible of student scores on the given resources
                   2167: 
                   2168: =cut
                   2169: 
                   2170: ########################################################
                   2171: ########################################################
                   2172: sub score_stats {
                   2173:     my ($Sections,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
                   2174:     if (! defined($courseid)) {
1.146     albertel 2175:         $courseid = $env{'request.course.id'};
1.129     matthew  2176:     }
                   2177:     #
                   2178:     &setup_table_names($courseid);
                   2179:     my $dbh = &Apache::lonmysql::get_dbh();
                   2180:     #
                   2181:     my ($section_limits,$enrollment_limits)=
                   2182:         &limit_by_section_and_status($Sections,$enrollment,'b');
                   2183:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
                   2184:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
                   2185:     #
                   2186:     my $stats_table = $courseid.'_problem_stats';
                   2187:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
                   2188:     my $request = 'DROP TABLE '.$stats_table;
                   2189:     $dbh->do($request);
                   2190:     $request = 
                   2191:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2192:         'SELECT a.student_id,'.
                   2193:         'SUM(a.awarded*w.weight) AS score FROM '.
                   2194:         $performance_table.' AS a '.
                   2195:         'NATURAL LEFT JOIN '.$weight_table.' AS w '.
                   2196:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
                   2197:         'WHERE ('.$symb_restriction.')';
                   2198:     if ($time_limits) {
                   2199:         $request .= ' AND '.$time_limits;
                   2200:     }
                   2201:     if ($section_limits) {
                   2202:         $request .= ' AND '.$section_limits;
                   2203:     }
                   2204:     if ($enrollment_limits) {
                   2205:         $request .= ' AND '.$enrollment_limits;
                   2206:     }
                   2207:     $request .= ' GROUP BY a.student_id';
                   2208: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2209:     my $sth = $dbh->prepare($request);
                   2210:     $sth->execute();
                   2211:     $request = 
                   2212:         'SELECT AVG(score),STD(score),MAX(score),MIN(score),COUNT(score) '.
                   2213:         'FROM '.$stats_table;
                   2214:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
                   2215: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2216:     
                   2217:     $request = 'SELECT SUM(weight) FROM '.$weight_table.
1.152     bowersj2 2218:         ' AS a WHERE ('.$symb_restriction.')';
1.129     matthew  2219:     my ($max_possible) = &execute_SQL_request($dbh,$request);
                   2220:     # &Apache::lonnet::logthis('request = '.$/.$request);
                   2221:     return($min,$max,$ave,$std,$count,$max_possible);
                   2222: }
                   2223: 
                   2224: 
                   2225: ########################################################
                   2226: ########################################################
                   2227: 
                   2228: =pod
                   2229: 
                   2230: =item &count_stats
                   2231: 
                   2232: Inputs: $Sections, $enrollment, $symbs, $starttime,
                   2233:         $endtime, $courseid
                   2234: 
                   2235: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
                   2236: elsewhere in this module.  
                   2237: $symbs is an array ref of symbs
                   2238: 
                   2239: Returns: minimum, maximum, mean, s.d., and number of students
                   2240:   of the number of items correct on the given resources
                   2241: 
                   2242: =cut
                   2243: 
                   2244: ########################################################
                   2245: ########################################################
                   2246: sub count_stats {
                   2247:     my ($Sections,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
                   2248:     if (! defined($courseid)) {
1.146     albertel 2249:         $courseid = $env{'request.course.id'};
1.129     matthew  2250:     }
                   2251:     #
                   2252:     &setup_table_names($courseid);
                   2253:     my $dbh = &Apache::lonmysql::get_dbh();
                   2254:     #
                   2255:     my ($section_limits,$enrollment_limits)=
                   2256:         &limit_by_section_and_status($Sections,$enrollment,'b');
                   2257:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
                   2258:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
                   2259:     #
                   2260:     my $stats_table = $courseid.'_problem_stats';
                   2261:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
                   2262:     my $request = 'DROP TABLE '.$stats_table;
                   2263:     $dbh->do($request);
                   2264:     $request = 
                   2265:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2266:         'SELECT a.student_id,'.
1.151     albertel 2267:         'SUM(a.awarded) AS count FROM '.
1.129     matthew  2268:         $performance_table.' AS a '.
                   2269:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
1.151     albertel 2270:         'WHERE ('.$symb_restriction.')';
1.129     matthew  2271:     if ($time_limits) {
                   2272:         $request .= ' AND '.$time_limits;
                   2273:     }
                   2274:     if ($section_limits) {
                   2275:         $request .= ' AND '.$section_limits;
                   2276:     }
                   2277:     if ($enrollment_limits) {
                   2278:         $request .= ' AND '.$enrollment_limits;
                   2279:     }
                   2280:     $request .= ' GROUP BY a.student_id';
1.131     matthew  2281: #    &Apache::lonnet::logthis('request = '.$/.$request);
1.129     matthew  2282:     my $sth = $dbh->prepare($request);
                   2283:     $sth->execute();
                   2284:     $request = 
                   2285:         'SELECT AVG(count),STD(count),MAX(count),MIN(count),COUNT(count) '.
                   2286:         'FROM '.$stats_table;
                   2287:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
1.131     matthew  2288: #    &Apache::lonnet::logthis('request = '.$/.$request);
1.129     matthew  2289:     return($min,$max,$ave,$std,$count);
                   2290: }
1.127     matthew  2291: 
                   2292: ######################################################
                   2293: ######################################################
                   2294: 
                   2295: =pod
                   2296: 
                   2297: =item get_student_data
                   2298: 
                   2299: =cut
                   2300: 
                   2301: ######################################################
                   2302: ######################################################
1.105     matthew  2303: sub get_student_data {
                   2304:     my ($students,$courseid) = @_;
1.146     albertel 2305:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.105     matthew  2306:     &setup_table_names($courseid);
                   2307:     my $dbh = &Apache::lonmysql::get_dbh();
                   2308:     return undef if (! defined($dbh));
                   2309:     my $request = 'SELECT '.
                   2310:         'student_id, student '.
                   2311:         'FROM '.$student_table;
                   2312:     if (defined($students)) {
                   2313:         $request .= ' WHERE ('.
                   2314:             join(' OR ', map {'student_id='.
                   2315:                                   &get_student_id($_->{'username'},
                   2316:                                                   $_->{'domain'})
                   2317:                               } @$students
                   2318:                  ).')';
                   2319:     }
                   2320:     $request.= ' ORDER BY student_id';
                   2321:     my $sth = $dbh->prepare($request);
                   2322:     $sth->execute();
                   2323:     if ($dbh->err) {
1.138     matthew  2324:         &Apache::lonnet::logthis('error 2 = '.$dbh->errstr());
                   2325:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.105     matthew  2326:         return undef;
                   2327:     }
                   2328:     my $dataset = $sth->fetchall_arrayref();
                   2329:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2330:         return $dataset;
                   2331:     }
                   2332: }
                   2333: 
1.108     matthew  2334: sub RD_student_id    { return 0; }
                   2335: sub RD_awarddetail   { return 1; }
                   2336: sub RD_response_eval { return 2; }
                   2337: sub RD_submission    { return 3; }
                   2338: sub RD_timestamp     { return 4; }
                   2339: sub RD_tries         { return 5; }
                   2340: sub RD_sname         { return 6; }
                   2341: 
                   2342: sub get_response_data {
1.126     matthew  2343:     my ($Sections,$enrollment,$symb,$response,$courseid) = @_;
1.103     matthew  2344:     return undef if (! defined($symb) || 
1.100     matthew  2345:                ! defined($response));
1.146     albertel 2346:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.100     matthew  2347:     #
                   2348:     &setup_table_names($courseid);
                   2349:     my $symb_id = &get_symb_id($symb);
1.137     matthew  2350:     if (! defined($symb_id)) {
                   2351:         &Apache::lonnet::logthis('Unable to find symb for '.$symb.' in '.$courseid);
                   2352:         return undef;
                   2353:     }
1.100     matthew  2354:     my $response_id = &get_part_id($response);
1.137     matthew  2355:     if (! defined($response_id)) {
                   2356:         &Apache::lonnet::logthis('Unable to find id for '.$response.' in '.$courseid);
                   2357:         return undef;
                   2358:     }
1.100     matthew  2359:     #
                   2360:     my $dbh = &Apache::lonmysql::get_dbh();
                   2361:     return undef if (! defined($dbh));
1.126     matthew  2362:     #
1.127     matthew  2363:     my ($student_requirements,$enrollment_requirements) = 
                   2364:         &limit_by_section_and_status($Sections,$enrollment,'d');
1.100     matthew  2365:     my $request = 'SELECT '.
1.105     matthew  2366:         'a.student_id, a.awarddetail, a.response_specific_value, '.
1.108     matthew  2367:         'a.submission, b.timestamp, c.tries, d.student '.
1.100     matthew  2368:         'FROM '.$fulldump_response_table.' AS a '.
                   2369:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2370:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2371:         'a.transaction = b.transaction '.
                   2372:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2373:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2374:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
1.108     matthew  2375:         'LEFT JOIN '.$student_table.' AS d '.
                   2376:         'ON a.student_id=d.student_id '.
1.100     matthew  2377:         'WHERE '.
                   2378:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
1.126     matthew  2379:     if (defined($student_requirements) || defined($enrollment_requirements)) {
                   2380:         $request .= ' AND ';
                   2381:         if (defined($student_requirements)) {
                   2382:             $request .= $student_requirements.' AND ';
                   2383:         }
                   2384:         if (defined($enrollment_requirements)) {
                   2385:             $request .= $enrollment_requirements.' AND ';
                   2386:         }
                   2387:         $request =~ s/( AND )$//;
1.100     matthew  2388:     }
                   2389:     $request .= ' ORDER BY b.timestamp';
1.103     matthew  2390: #    &Apache::lonnet::logthis("request =\n".$request);
1.100     matthew  2391:     my $sth = $dbh->prepare($request);
                   2392:     $sth->execute();
1.105     matthew  2393:     if ($dbh->err) {
1.138     matthew  2394:         &Apache::lonnet::logthis('error 3 = '.$dbh->errstr());
                   2395:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.105     matthew  2396:         return undef;
                   2397:     }
1.100     matthew  2398:     my $dataset = $sth->fetchall_arrayref();
                   2399:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
1.117     matthew  2400:         # Clear the \'s from around the submission
                   2401:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2402:             $dataset->[$i]->[3] =~ s/(\'$|^\')//g;
                   2403:         }
1.103     matthew  2404:         return $dataset;
1.100     matthew  2405:     }
1.118     matthew  2406: }
                   2407: 
                   2408: 
                   2409: sub RDs_awarddetail   { return 3; }
                   2410: sub RDs_submission    { return 2; }
                   2411: sub RDs_timestamp     { return 1; }
                   2412: sub RDs_tries         { return 0; }
1.119     matthew  2413: sub RDs_awarded       { return 4; }
1.118     matthew  2414: 
                   2415: sub get_response_data_by_student {
                   2416:     my ($student,$symb,$response,$courseid) = @_;
                   2417:     return undef if (! defined($symb) || 
                   2418:                      ! defined($response));
1.146     albertel 2419:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.118     matthew  2420:     #
                   2421:     &setup_table_names($courseid);
                   2422:     my $symb_id = &get_symb_id($symb);
                   2423:     my $response_id = &get_part_id($response);
                   2424:     #
                   2425:     my $student_id = &get_student_id($student->{'username'},
                   2426:                                      $student->{'domain'});
                   2427:     #
                   2428:     my $dbh = &Apache::lonmysql::get_dbh();
                   2429:     return undef if (! defined($dbh));
                   2430:     my $request = 'SELECT '.
1.119     matthew  2431:         'c.tries, b.timestamp, a.submission, a.awarddetail, e.awarded '.
1.118     matthew  2432:         'FROM '.$fulldump_response_table.' AS a '.
                   2433:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2434:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2435:         'a.transaction = b.transaction '.
                   2436:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2437:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2438:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
                   2439:         'LEFT JOIN '.$student_table.' AS d '.
                   2440:         'ON a.student_id=d.student_id '.
1.119     matthew  2441:         'LEFT JOIN '.$performance_table.' AS e '.
                   2442:         'ON a.symb_id=e.symb_id AND a.part_id=e.part_id AND '.
                   2443:         'a.student_id=e.student_id AND c.tries=e.tries '.
1.118     matthew  2444:         'WHERE '.
                   2445:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id.
                   2446:         ' AND a.student_id='.$student_id.' ORDER BY b.timestamp';
1.125     matthew  2447: #    &Apache::lonnet::logthis("request =\n".$request);
1.118     matthew  2448:     my $sth = $dbh->prepare($request);
                   2449:     $sth->execute();
                   2450:     if ($dbh->err) {
1.138     matthew  2451:         &Apache::lonnet::logthis('error 4 = '.$dbh->errstr());
                   2452:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.118     matthew  2453:         return undef;
                   2454:     }
                   2455:     my $dataset = $sth->fetchall_arrayref();
                   2456:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2457:         # Clear the \'s from around the submission
                   2458:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2459:             $dataset->[$i]->[2] =~ s/(\'$|^\')//g;
                   2460:         }
                   2461:         return $dataset;
                   2462:     }
                   2463:     return undef; # error occurred
1.106     matthew  2464: }
1.108     matthew  2465: 
                   2466: sub RT_student_id { return 0; }
                   2467: sub RT_awarded    { return 1; }
                   2468: sub RT_tries      { return 2; }
                   2469: sub RT_timestamp  { return 3; }
1.106     matthew  2470: 
                   2471: sub get_response_time_data {
1.142     matthew  2472:     my ($sections,$enrollment,$symb,$part,$courseid) = @_;
1.106     matthew  2473:     return undef if (! defined($symb) || 
1.107     matthew  2474:                      ! defined($part));
1.146     albertel 2475:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.106     matthew  2476:     #
                   2477:     &setup_table_names($courseid);
                   2478:     my $symb_id = &get_symb_id($symb);
1.142     matthew  2479:     if (! defined($symb_id)) {
                   2480:         &Apache::lonnet::logthis('Unable to find symb for '.$symb.' in '.$courseid);
                   2481:         return undef;
                   2482:     }
1.107     matthew  2483:     my $part_id = &get_part_id($part);
1.142     matthew  2484:     if (! defined($part_id)) {
                   2485:         &Apache::lonnet::logthis('Unable to find id for '.$part.' in '.$courseid);
                   2486:         return undef;
                   2487:     }
1.106     matthew  2488:     #
                   2489:     my $dbh = &Apache::lonmysql::get_dbh();
                   2490:     return undef if (! defined($dbh));
1.142     matthew  2491:     my ($student_requirements,$enrollment_requirements) = 
                   2492:         &limit_by_section_and_status($sections,$enrollment,'d');
1.106     matthew  2493:     my $request = 'SELECT '.
1.107     matthew  2494:         'a.student_id, a.awarded, a.tries, b.timestamp '.
                   2495:         'FROM '.$fulldump_part_table.' AS a '.
1.142     matthew  2496:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2497:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2498:         'a.transaction = b.transaction '.
                   2499:         'LEFT JOIN '.$student_table.' as d '.
                   2500:         'ON a.student_id=d.student_id '.
1.106     matthew  2501:         'WHERE '.
1.107     matthew  2502:         'a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.142     matthew  2503:     if (defined($student_requirements) || defined($enrollment_requirements)) {
                   2504:         $request .= ' AND ';
                   2505:         if (defined($student_requirements)) {
                   2506:             $request .= $student_requirements.' AND ';
                   2507:         }
                   2508:         if (defined($enrollment_requirements)) {
                   2509:             $request .= $enrollment_requirements.' AND ';
                   2510:         }
                   2511:         $request =~ s/( AND )$//;
1.106     matthew  2512:     }
                   2513:     $request .= ' ORDER BY b.timestamp';
                   2514: #    &Apache::lonnet::logthis("request =\n".$request);
                   2515:     my $sth = $dbh->prepare($request);
                   2516:     $sth->execute();
                   2517:     if ($dbh->err) {
1.138     matthew  2518:         &Apache::lonnet::logthis('error 5 = '.$dbh->errstr());
                   2519:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.106     matthew  2520:         return undef;
                   2521:     }
                   2522:     my $dataset = $sth->fetchall_arrayref();
                   2523:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2524:         return $dataset;
                   2525:     }
                   2526: 
1.100     matthew  2527: }
1.61      matthew  2528: 
                   2529: ################################################
                   2530: ################################################
                   2531: 
                   2532: =pod
                   2533: 
1.116     matthew  2534: =item &get_student_scores($Sections,$Symbs,$enrollment,$courseid)
1.113     matthew  2535: 
                   2536: =cut
                   2537: 
                   2538: ################################################
                   2539: ################################################
                   2540: sub get_student_scores {
1.145     matthew  2541:     my ($sections,$Symbs,$enrollment,$courseid,$starttime,$endtime) = @_;
1.146     albertel 2542:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.113     matthew  2543:     &setup_table_names($courseid);
                   2544:     my $dbh = &Apache::lonmysql::get_dbh();
                   2545:     return (undef) if (! defined($dbh));
                   2546:     my $tmptable = $courseid.'_temp_'.time;
1.145     matthew  2547:     my $request = 'DROP TABLE IF EXISTS '.$tmptable;
                   2548: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2549:     $dbh->do($request);
1.114     matthew  2550:     #
                   2551:     my $symb_requirements;
1.113     matthew  2552:     if (defined($Symbs)  && @$Symbs) {
                   2553:         $symb_requirements = '('.
1.114     matthew  2554:             join(' OR ', map{ "(a.symb_id='".&get_symb_id($_->{'symb'}).
1.121     matthew  2555:                               "' AND a.part_id='".&get_part_id($_->{'part'}).
                   2556:                               "')"
1.113     matthew  2557:                               } @$Symbs).')';
                   2558:     }
1.114     matthew  2559:     #
1.145     matthew  2560:     my ($student_requirements,$enrollment_requirements) = 
                   2561:         &limit_by_section_and_status($sections,$enrollment,'b');
1.114     matthew  2562:     #
1.145     matthew  2563:     my $time_requirements = &limit_by_start_end_time($starttime,$endtime,'a');
1.114     matthew  2564:     ##
1.145     matthew  2565:     $request = 'CREATE TEMPORARY TABLE IF NOT EXISTS '.$tmptable.
                   2566:         ' SELECT a.student_id,SUM(a.awarded*c.weight) AS score FROM '.
1.114     matthew  2567:         $performance_table.' AS a ';
1.145     matthew  2568:     $request .= "LEFT JOIN ".$weight_table.' AS c ON a.symb_id=c.symb_id AND a.part_id=c.part_id ';
1.114     matthew  2569:     if (defined($student_requirements) || defined($enrollment_requirements)) {
1.145     matthew  2570:         $request .= ' LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id';
1.114     matthew  2571:     }
                   2572:     if (defined($symb_requirements)      || 
                   2573:         defined($student_requirements)   ||
                   2574:         defined($enrollment_requirements) ) {
1.113     matthew  2575:         $request .= ' WHERE ';
                   2576:     }
1.114     matthew  2577:     if (defined($symb_requirements)) {
                   2578:         $request .= $symb_requirements.' AND ';
                   2579:     }
                   2580:     if (defined($student_requirements)) {
                   2581:         $request .= $student_requirements.' AND ';
                   2582:     }
                   2583:     if (defined($enrollment_requirements)) {
                   2584:         $request .= $enrollment_requirements.' AND ';
                   2585:     }
1.121     matthew  2586:     if (defined($time_requirements)) {
                   2587:         $request .= $time_requirements.' AND ';
                   2588:     }
                   2589:     $request =~ s/ AND $//; # Strip of the trailing ' AND '.
1.114     matthew  2590:     $request .= ' GROUP BY a.student_id';
                   2591: #    &Apache::lonnet::logthis("request = \n".$request);
1.113     matthew  2592:     my $sth = $dbh->prepare($request);
                   2593:     $sth->execute();
                   2594:     if ($dbh->err) {
1.138     matthew  2595:         &Apache::lonnet::logthis('error 6 = '.$dbh->errstr());
                   2596:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.113     matthew  2597:         return undef;
                   2598:     }
                   2599:     $request = 'SELECT score,COUNT(*) FROM '.$tmptable.' GROUP BY score';
                   2600: #    &Apache::lonnet::logthis("request = \n".$request);
                   2601:     $sth = $dbh->prepare($request);
                   2602:     $sth->execute();
                   2603:     if ($dbh->err) {
1.138     matthew  2604:         &Apache::lonnet::logthis('error 7 = '.$dbh->errstr());
                   2605:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.113     matthew  2606:         return undef;
                   2607:     }
                   2608:     my $dataset = $sth->fetchall_arrayref();
                   2609:     return $dataset;
                   2610: }
                   2611: 
                   2612: ################################################
                   2613: ################################################
                   2614: 
                   2615: =pod
                   2616: 
1.61      matthew  2617: =item &setup_table_names()
                   2618: 
                   2619: input: course id
                   2620: 
                   2621: output: none
                   2622: 
                   2623: Cleans up the package variables for local caching.
                   2624: 
                   2625: =cut
                   2626: 
                   2627: ################################################
                   2628: ################################################
                   2629: sub setup_table_names {
                   2630:     my ($courseid) = @_;
                   2631:     if (! defined($courseid)) {
1.146     albertel 2632:         $courseid = $env{'request.course.id'};
1.61      matthew  2633:     }
                   2634:     #
                   2635:     if (! defined($current_course) || $current_course ne $courseid) {
                   2636:         # Clear out variables
                   2637:         $have_read_part_table = 0;
                   2638:         undef(%ids_by_part);
                   2639:         undef(%parts_by_id);
                   2640:         $have_read_symb_table = 0;
                   2641:         undef(%ids_by_symb);
                   2642:         undef(%symbs_by_id);
                   2643:         $have_read_student_table = 0;
                   2644:         undef(%ids_by_student);
                   2645:         undef(%students_by_id);
                   2646:         #
                   2647:         $current_course = $courseid;
                   2648:     }
                   2649:     #
                   2650:     # Set up database names
                   2651:     my $base_id = $courseid;
                   2652:     $symb_table        = $base_id.'_'.'symb';
                   2653:     $part_table        = $base_id.'_'.'part';
                   2654:     $student_table     = $base_id.'_'.'student';
                   2655:     $performance_table = $base_id.'_'.'performance';
                   2656:     $parameters_table  = $base_id.'_'.'parameters';
1.89      matthew  2657:     $fulldump_part_table      = $base_id.'_'.'partdata';
                   2658:     $fulldump_response_table  = $base_id.'_'.'responsedata';
                   2659:     $fulldump_timestamp_table = $base_id.'_'.'timestampdata';
1.127     matthew  2660:     $weight_table             = $base_id.'_'.'weight';
1.89      matthew  2661:     #
                   2662:     @Tables = (
                   2663:                $symb_table,
                   2664:                $part_table,
                   2665:                $student_table,
                   2666:                $performance_table,
                   2667:                $parameters_table,
                   2668:                $fulldump_part_table,
                   2669:                $fulldump_response_table,
                   2670:                $fulldump_timestamp_table,
1.127     matthew  2671:                $weight_table,
1.89      matthew  2672:                );
1.61      matthew  2673:     return;
1.3       stredwic 2674: }
1.1       stredwic 2675: 
1.35      matthew  2676: ################################################
                   2677: ################################################
                   2678: 
                   2679: =pod
                   2680: 
1.57      matthew  2681: =back
                   2682: 
                   2683: =item End of Local Data Caching Subroutines
                   2684: 
                   2685: =cut
                   2686: 
                   2687: ################################################
                   2688: ################################################
                   2689: 
1.89      matthew  2690: } # End scope of table identifiers
1.57      matthew  2691: 
                   2692: ################################################
                   2693: ################################################
                   2694: 
                   2695: =pod
                   2696: 
                   2697: =head3 Classlist Subroutines
                   2698: 
1.35      matthew  2699: =item &get_classlist();
                   2700: 
                   2701: Retrieve the classist of a given class or of the current class.  Student
                   2702: information is returned from the classlist.db file and, if needed,
                   2703: from the students environment.
                   2704: 
1.150     albertel 2705: Optional arguments are $cdom, and $cnum (course domain,
                   2706: and course number, respectively).  If either is ommitted the course
                   2707: will be taken from the current environment ($env{'request.course.id'},
1.146     albertel 2708: $env{'course.'.$cid.'.domain'}, and $env{'course.'.$cid.'.num'}).
1.35      matthew  2709: 
                   2710: Returns a reference to a hash which contains:
                   2711:  keys    '$sname:$sdom'
1.136     raeburn  2712:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type,$lockedtype]
1.54      bowersj2 2713: 
                   2714: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
                   2715: as indices into the returned list to future-proof clients against
                   2716: changes in the list order.
1.35      matthew  2717: 
                   2718: =cut
                   2719: 
                   2720: ################################################
                   2721: ################################################
1.54      bowersj2 2722: 
                   2723: sub CL_SDOM     { return 0; }
                   2724: sub CL_SNAME    { return 1; }
                   2725: sub CL_END      { return 2; }
                   2726: sub CL_START    { return 3; }
                   2727: sub CL_ID       { return 4; }
                   2728: sub CL_SECTION  { return 5; }
                   2729: sub CL_FULLNAME { return 6; }
                   2730: sub CL_STATUS   { return 7; }
1.111     raeburn  2731: sub CL_TYPE     { return 8; }
1.136     raeburn  2732: sub CL_LOCKEDTYPE   { return 9; }
1.35      matthew  2733: 
                   2734: sub get_classlist {
1.150     albertel 2735:     my ($cdom,$cnum) = @_;
                   2736:     my $cid = $cdom.'_'.$cnum;
                   2737:     if (!defined($cdom) || !defined($cnum)) {
                   2738: 	$cid =  $env{'request.course.id'};
                   2739: 	$cdom = $env{'course.'.$cid.'.domain'};
                   2740: 	$cnum = $env{'course.'.$cid.'.num'};
                   2741:     }
1.57      matthew  2742:     my $now = time;
1.35      matthew  2743:     #
                   2744:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
                   2745:     while (my ($student,$info) = each(%classlist)) {
1.60      matthew  2746:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
                   2747:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
                   2748:             return undef;
                   2749:         }
1.35      matthew  2750:         my ($sname,$sdom) = split(/:/,$student);
                   2751:         my @Values = split(/:/,$info);
1.136     raeburn  2752:         my ($end,$start,$id,$section,$fullname,$type,$lockedtype);
1.35      matthew  2753:         if (@Values > 2) {
1.136     raeburn  2754:             ($end,$start,$id,$section,$fullname,$type,$lockedtype) = @Values;
1.35      matthew  2755:         } else { # We have to get the data ourselves
                   2756:             ($end,$start) = @Values;
1.37      matthew  2757:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
1.35      matthew  2758:             my %info=&Apache::lonnet::get('environment',
                   2759:                                           ['firstname','middlename',
                   2760:                                            'lastname','generation','id'],
                   2761:                                           $sdom, $sname);
                   2762:             my ($tmp) = keys(%info);
                   2763:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   2764:                 $fullname = 'not available';
                   2765:                 $id = 'not available';
1.38      matthew  2766:                 &Apache::lonnet::logthis('unable to retrieve environment '.
                   2767:                                          'for '.$sname.':'.$sdom);
1.35      matthew  2768:             } else {
1.141     albertel 2769:                 $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
1.35      matthew  2770:                 $id = $info{'id'};
                   2771:             }
1.36      matthew  2772:             # Update the classlist with this students information
                   2773:             if ($fullname ne 'not available') {
1.141     albertel 2774: 		my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
                   2775: 		my $reply=&Apache::lonnet::cput('classlist',
1.36      matthew  2776:                                                 {$student => $enrolldata},
                   2777:                                                 $cdom,$cnum);
                   2778:                 if ($reply !~ /^(ok|delayed)/) {
                   2779:                     &Apache::lonnet::logthis('Unable to update classlist for '.
                   2780:                                              'student '.$sname.':'.$sdom.
                   2781:                                              ' error:'.$reply);
                   2782:                 }
                   2783:             }
1.35      matthew  2784:         }
                   2785:         my $status='Expired';
                   2786:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
                   2787:             $status='Active';
                   2788:         }
                   2789:         $classlist{$student} = 
1.136     raeburn  2790:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type,$lockedtype];
1.35      matthew  2791:     }
                   2792:     if (wantarray()) {
                   2793:         return (\%classlist,['domain','username','end','start','id',
1.136     raeburn  2794:                              'section','fullname','status','type','lockedtype']);
1.35      matthew  2795:     } else {
                   2796:         return \%classlist;
                   2797:     }
                   2798: }
                   2799: 
1.1       stredwic 2800: # ----- END HELPER FUNCTIONS --------------------------------------------
                   2801: 
                   2802: 1;
                   2803: __END__
1.36      matthew  2804: 
1.35      matthew  2805: 

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