File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.168: download - view: text, annotated - select for diffs
Fri May 5 21:35:31 2006 UTC (18 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
A couple of ANDs missing from the SQL WHERE conditions for group limits.

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

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