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

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

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