File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.164: download - view: text, annotated - select for diffs
Fri Apr 28 21:58:37 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- .task 'version' is really tries for them
- 'correct_by_override' is the normal stat of affairs for a .task

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

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