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

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

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