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