File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.173: download - view: text, annotated - select for diffs
Tue May 30 12:46:09 2006 UTC (18 years ago) by www
Branches: MAIN
CVS tags: version_2_1_99_2, version_2_1_99_1, version_2_1_99_0, HEAD
&Apache::lonnet::unescape -> &unescape
&Apache::lonnet::escape -> &escape

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

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