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

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

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