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

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

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