1: # The LearningOnline Network with CAPA
2: #
3: # $Id: loncoursedata.pm,v 1.57 2003/03/17 22:52:04 matthew Exp $
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:
37: Set of functions that download and process student and course information.
38:
39: =head1 PACKAGES USED
40:
41: Apache::Constants qw(:common :http)
42: Apache::lonnet()
43: Apache::lonhtmlcommon
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();
54: use Apache::lonhtmlcommon;
55: use Time::HiRes;
56: use Apache::lonmysql;
57: use HTML::TokeParser;
58: use GDBM_File;
59:
60: =pod
61:
62: =head1 DOWNLOAD INFORMATION
63:
64: This section contains all the functions that get data from other servers
65: and/or itself.
66:
67: =cut
68:
69: # ----- DOWNLOAD INFORMATION -------------------------------------------
70:
71: =pod
72:
73: =item &DownloadClasslist()
74:
75: Collects lastname, generation, middlename, firstname, PID, and section for each
76: student from their environment database. The section data is also download, though
77: it is in a rough format, and is processed later. The list of students is built from
78: collecting a classlist for the course that is to be displayed. Once the classlist
79: has been downloaded, its date stamp is recorded. Unless the datestamp for the
80: class database is reset or is modified, this data will not be downloaded again.
81: Also, there was talk about putting the fullname and section
82: and perhaps other pieces of data into the classlist file. This would
83: reduce the number of different file accesses and reduce the amount of
84: processing on this side.
85:
86: =over 4
87:
88: Input: $courseID, $lastDownloadTime, $c
89:
90: $courseID: The id of the course
91:
92: $lastDownloadTime: This is the date stamp for when this information was
93: last gathered. If it is set to Not downloaded, it will gather the data
94: again, though it currently does not remove the old data.
95:
96: $c: The connection class that can determine if the browser has aborted. It
97: is used to short circuit this function so that it does not continue to
98: get information when there is no need.
99:
100: Output: \%classlist
101:
102: \%classlist: A pointer to a hash containing the following data:
103:
104: -A list of student name:domain (as keys) (known below as $name)
105:
106: -A hash pointer for each student containing lastname, generation, firstname,
107: middlename, and PID : Key is $name.studentInformation
108:
109: -A hash pointer to each students section data : Key is $name.section
110:
111: -If there was an error in dump, it will be returned in the hash. See
112: the error codes for dump in lonnet. Also, an error key will be
113: generated if an abort occurs.
114:
115: =back
116:
117: =cut
118:
119: sub DownloadClasslist {
120: my ($courseID, $lastDownloadTime, $c)=@_;
121: my ($courseDomain,$courseNumber)=split(/\_/,$courseID);
122: my %classlist;
123:
124: my $modifiedTime = &Apache::lonnet::GetFileTimestamp($courseDomain,
125: $courseNumber,
126: 'classlist.db',
127: $Apache::lonnet::perlvar{'lonUsersDir'});
128:
129: # Always download the information if lastDownloadTime is set to
130: # Not downloaded, otherwise it is only downloaded if the file
131: # has been updated and has a more recent date stamp
132: if($lastDownloadTime ne 'Not downloaded' &&
133: $lastDownloadTime >= $modifiedTime && $modifiedTime >= 0) {
134: # Data is not gathered so return UpToDate as true. This
135: # will be interpreted in ProcessClasslist
136: $classlist{'lastDownloadTime'}=time;
137: $classlist{'UpToDate'} = 'true';
138: return \%classlist;
139: }
140:
141: %classlist=&Apache::lonnet::dump('classlist',$courseDomain, $courseNumber);
142: foreach(keys (%classlist)) {
143: if(/^(con_lost|error|no_such_host)/i) {
144: return;
145: }
146: }
147:
148: foreach my $name (keys(%classlist)) {
149: if(defined($c) && ($c->aborted())) {
150: $classlist{'error'}='aborted';
151: return \%classlist;
152: }
153:
154: my ($studentName,$studentDomain) = split(/\:/,$name);
155: # Download student environment data, specifically the full name and id.
156: my %studentInformation=&Apache::lonnet::get('environment',
157: ['lastname','generation',
158: 'firstname','middlename',
159: 'id'],
160: $studentDomain,
161: $studentName);
162: $classlist{$name.':studentInformation'}=\%studentInformation;
163:
164: if($c->aborted()) {
165: $classlist{'error'}='aborted';
166: return \%classlist;
167: }
168:
169: #Section
170: my %section=&Apache::lonnet::dump('roles',$studentDomain,$studentName);
171: $classlist{$name.':sections'}=\%section;
172: }
173:
174: $classlist{'UpToDate'} = 'false';
175: $classlist{'lastDownloadTime'}=time;
176:
177: return \%classlist;
178: }
179:
180: =pod
181:
182: =item &DownloadCourseInformation()
183:
184: Dump of all the course information for a single student. The data can be
185: pruned by making use of dumps regular expression arguement. This function
186: also takes a regular expression which it passes straight through to dump.
187: The data is no escaped, because it is done elsewhere. It also
188: checks the timestamp of the students course database file and only downloads
189: if it has been modified since the last download.
190:
191: =over 4
192:
193: Input: $namedata, $courseID, $lastDownloadTime, $WhatIWant
194:
195: $namedata: student name:domain
196:
197: $courseID: The id of the course
198:
199: $lastDownloadTime: This is the date stamp for when this information was
200: last gathered. If it is set to Not downloaded, it will gather the data
201: again, though it currently does not remove the old data.
202:
203: $WhatIWant: Regular expression used to get selected data with dump
204:
205: Output: \%courseData
206:
207: \%courseData: A hash pointer to the raw data from the students course
208: database.
209:
210: =back
211:
212: =cut
213:
214: sub DownloadCourseInformation {
215: my ($namedata,$courseID,$lastDownloadTime,$WhatIWant)=@_;
216: my %courseData;
217: my ($name,$domain) = split(/\:/,$namedata);
218:
219: my $modifiedTime = &Apache::lonnet::GetFileTimestamp($domain, $name,
220: $courseID.'.db',
221: $Apache::lonnet::perlvar{'lonUsersDir'});
222:
223: if($lastDownloadTime ne 'Not downloaded' &&
224: $lastDownloadTime >= $modifiedTime && $modifiedTime >= 0) {
225: # Data is not gathered so return UpToDate as true. This
226: # will be interpreted in ProcessClasslist
227: $courseData{$namedata.':lastDownloadTime'}=time;
228: $courseData{$namedata.':UpToDate'} = 'true';
229: return \%courseData;
230: }
231:
232: # Download course data
233: if(!defined($WhatIWant)) {
234: # set the regular expression to everything by setting it to period
235: $WhatIWant = '.';
236: }
237: %courseData=&Apache::lonnet::dump($courseID, $domain, $name, $WhatIWant);
238: $courseData{'UpToDate'} = 'false';
239: $courseData{'lastDownloadTime'}=time;
240:
241: my %newData;
242: foreach (keys(%courseData)) {
243: # need to have the keys to be prepended with the name:domain of the
244: # student to reduce data collision later.
245: $newData{$namedata.':'.$_} = $courseData{$_};
246: }
247:
248: return \%newData;
249: }
250:
251: # ----- END DOWNLOAD INFORMATION ---------------------------------------
252:
253: =pod
254:
255: =head1 PROCESSING FUNCTIONS
256:
257: These functions process all the data for all the students. Also, they
258: are the functions that access the cache database for writing the majority of
259: the time. The downloading and caching were separated to reduce problems
260: with stopping downloading then can not tie hash to database later.
261:
262: =cut
263:
264: # ----- PROCESSING FUNCTIONS ---------------------------------------
265:
266: ####################################################
267: ####################################################
268:
269: =pod
270:
271: =item &get_sequence_assessment_data()
272:
273: AT THIS TIME THE USE OF THIS FUNCTION IS *NOT* RECOMMENDED
274:
275: Use lonnavmaps to build a data structure describing the order and
276: assessment contents of each sequence in the current course.
277:
278: The returned structure is a hash reference.
279:
280: { title => 'title',
281: symb => 'symb',
282: source => '/s/o/u/r/c/e',
283: type => (container|assessment),
284: num_assess => 2, # only for container
285: parts => [11,13,15], # only for assessment
286: response_ids => [12,14,16], # only for assessment
287: contents => [........] # only for container
288: }
289:
290: $hash->{'contents'} is a reference to an array of hashes of the same structure.
291:
292: Also returned are array references to the sequences and assessments contained
293: in the course.
294:
295:
296: =cut
297:
298: ####################################################
299: ####################################################
300: sub get_sequence_assessment_data {
301: my $fn=$ENV{'request.course.fn'};
302: ##
303: ## use navmaps
304: my $navmap = Apache::lonnavmaps::navmap->new($fn.".db",$fn."_parms.db",
305: 1,0);
306: if (!defined($navmap)) {
307: return 'Can not open Coursemap';
308: }
309: my $iterator = $navmap->getIterator(undef, undef, undef, 1);
310: ##
311: ## Prime the pump
312: ##
313: ## We are going to loop until we run out of sequences/pages to explore for
314: ## resources. This means we have to start out with something to look
315: ## at.
316: my $title = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
317: my $symb = 'top';
318: my $src = 'not applicable';
319: #
320: my @Sequences;
321: my @Assessments;
322: my @Nested_Sequences = (); # Stack of sequences, keeps track of depth
323: my $top = { title => $title,
324: src => $src,
325: symb => $symb,
326: type => 'container',
327: num_assess => 0,
328: num_assess_parts => 0,
329: contents => [], };
330: push (@Sequences,$top);
331: push (@Nested_Sequences, $top);
332: #
333: # We need to keep track of which sequences contain homework problems
334: #
335: my $previous;
336: my $curRes = $iterator->next(); # BEGIN_MAP
337: $curRes = $iterator->next(); # The first item in the top level map.
338: while (scalar(@Nested_Sequences)) {
339: $previous = $curRes;
340: $curRes = $iterator->next();
341: my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
342: if ($curRes == $iterator->BEGIN_MAP()) {
343: # get the map itself, instead of BEGIN_MAP
344: $title = $previous->title();
345: $symb = $previous->symb();
346: $src = $previous->src();
347: my $newmap = { title => $title,
348: src => $src,
349: symb => $symb,
350: type => 'container',
351: num_assess => 0,
352: contents => [],
353: };
354: push (@{$currentmap->{'contents'}},$newmap); # this is permanent
355: push (@Sequences,$newmap);
356: push (@Nested_Sequences, $newmap); # this is a stack
357: next;
358: }
359: if ($curRes == $iterator->END_MAP()) {
360: pop(@Nested_Sequences);
361: next;
362: }
363: next if (! ref($curRes));
364: next if (! $curRes->is_problem());# && !$curRes->randomout);
365: # Okay, from here on out we only deal with assessments
366: $title = $curRes->title();
367: $symb = $curRes->symb();
368: $src = $curRes->src();
369: my $parts = $curRes->parts();
370: my $assessment = { title => $title,
371: src => $src,
372: symb => $symb,
373: type => 'assessment',
374: parts => $parts,
375: num_parts => scalar(@$parts),
376: };
377: push(@Assessments,$assessment);
378: push(@{$currentmap->{'contents'}},$assessment);
379: $currentmap->{'num_assess'}++;
380: $currentmap->{'num_assess_parts'}+= scalar(@$parts);
381: }
382: return ($top,\@Sequences,\@Assessments);
383: }
384:
385: #################################################
386: #################################################
387:
388: =pod
389:
390: =item &ProcessTopResourceMap()
391:
392: Trace through the "big hash" created in rat/lonuserstate.pm::loadmap.
393: Basically, this function organizes a subset of the data and stores it in
394: cached data. The data stored is the problems, sequences, sequence titles,
395: parts of problems, and their ordering. Column width information is also
396: partially handled here on a per sequence basis.
397:
398: =over 4
399:
400: Input: $cache, $c
401:
402: $cache: A pointer to a hash to store the information
403:
404: $c: The connection class used to determine if an abort has been sent to the
405: browser
406:
407: Output: A string that contains an error message or "OK" if everything went
408: smoothly.
409:
410: =back
411:
412: =cut
413:
414: sub ProcessTopResourceMap {
415: my ($cache,$c)=@_;
416: my %hash;
417: my $fn=$ENV{'request.course.fn'};
418: if(-e "$fn.db") {
419: my $tieTries=0;
420: while($tieTries < 3) {
421: if($c->aborted()) {
422: return;
423: }
424: if(tie(%hash,'GDBM_File',"$fn.db",&GDBM_READER(),0640)) {
425: last;
426: }
427: $tieTries++;
428: sleep 1;
429: }
430: if($tieTries >= 3) {
431: return 'Coursemap undefined.';
432: }
433: } else {
434: return 'Can not open Coursemap.';
435: }
436:
437: my $oldkeys;
438: delete $cache->{'OptionResponses'};
439: if(defined($cache->{'ResourceKeys'})) {
440: $oldkeys = $cache->{'ResourceKeys'};
441: foreach (split(':::', $cache->{'ResourceKeys'})) {
442: delete $cache->{$_};
443: }
444: delete $cache->{'ResourceKeys'};
445: }
446:
447: # Initialize state machine. Set information pointing to top level map.
448: my (@sequences, @currentResource, @finishResource);
449: my ($currentSequence, $currentResourceID, $lastResourceID);
450:
451: $currentResourceID=$hash{'ids_'.
452: &Apache::lonnet::clutter($ENV{'request.course.uri'})};
453: push(@currentResource, $currentResourceID);
454: $lastResourceID=-1;
455: $currentSequence=-1;
456: my $topLevelSequenceNumber = $currentSequence;
457:
458: my %sequenceRecord;
459: my %allkeys;
460: while(1) {
461: if($c->aborted()) {
462: last;
463: }
464: # HANDLE NEW SEQUENCE!
465: #if page || sequence
466: if(defined($hash{'map_pc_'.$hash{'src_'.$currentResourceID}}) &&
467: !defined($sequenceRecord{$currentResourceID})) {
468: $sequenceRecord{$currentResourceID}++;
469: push(@sequences, $currentSequence);
470: push(@currentResource, $currentResourceID);
471: push(@finishResource, $lastResourceID);
472:
473: $currentSequence=$hash{'map_pc_'.$hash{'src_'.$currentResourceID}};
474:
475: # Mark sequence as containing problems. If it doesn't, then
476: # it will be removed when processing for this sequence is
477: # complete. This allows the problems in a sequence
478: # to be outputed before problems in the subsequences
479: if(!defined($cache->{'orderedSequences'})) {
480: $cache->{'orderedSequences'}=$currentSequence;
481: } else {
482: $cache->{'orderedSequences'}.=':'.$currentSequence;
483: }
484: $allkeys{'orderedSequences'}++;
485:
486: $lastResourceID=$hash{'map_finish_'.
487: $hash{'src_'.$currentResourceID}};
488: $currentResourceID=$hash{'map_start_'.
489: $hash{'src_'.$currentResourceID}};
490:
491: if(!($currentResourceID) || !($lastResourceID)) {
492: $currentSequence=pop(@sequences);
493: $currentResourceID=pop(@currentResource);
494: $lastResourceID=pop(@finishResource);
495: if($currentSequence eq $topLevelSequenceNumber) {
496: last;
497: }
498: }
499: next;
500: }
501:
502: # Handle gradable resources: exams, problems, etc
503: $currentResourceID=~/(\d+)\.(\d+)/;
504: my $partA=$1;
505: my $partB=$2;
506: if($hash{'src_'.$currentResourceID}=~
507: /\.(problem|exam|quiz|assess|survey|form)$/ &&
508: $partA eq $currentSequence &&
509: !defined($sequenceRecord{$currentSequence.':'.
510: $currentResourceID})) {
511: $sequenceRecord{$currentSequence.':'.$currentResourceID}++;
512: my $Problem = &Apache::lonnet::symbclean(
513: &Apache::lonnet::declutter($hash{'map_id_'.$partA}).
514: '___'.$partB.'___'.
515: &Apache::lonnet::declutter($hash{'src_'.
516: $currentResourceID}));
517:
518: $cache->{$currentResourceID.':problem'}=$Problem;
519: $allkeys{$currentResourceID.':problem'}++;
520: if(!defined($cache->{$currentSequence.':problems'})) {
521: $cache->{$currentSequence.':problems'}=$currentResourceID;
522: } else {
523: $cache->{$currentSequence.':problems'}.=
524: ':'.$currentResourceID;
525: }
526: $allkeys{$currentSequence.':problems'}++;
527:
528: my $meta=$hash{'src_'.$currentResourceID};
529: # $cache->{$currentResourceID.':title'}=
530: # &Apache::lonnet::metdata($meta,'title');
531: $cache->{$currentResourceID.':title'}=
532: $hash{'title_'.$currentResourceID};
533: $allkeys{$currentResourceID.':title'}++;
534: $cache->{$currentResourceID.':source'}=
535: $hash{'src_'.$currentResourceID};
536: $allkeys{$currentResourceID.':source'}++;
537:
538: # Get Parts for problem
539: my %beenHere;
540: foreach (split(/\,/,&Apache::lonnet::metadata($meta,'packages'))) {
541: if(/^\w+response_\d+.*/) {
542: my (undef, $partId, $responseId) = split(/_/,$_);
543: if($beenHere{'p:'.$partId} == 0) {
544: $beenHere{'p:'.$partId}++;
545: if(!defined($cache->{$currentSequence.':'.
546: $currentResourceID.':parts'})) {
547: $cache->{$currentSequence.':'.$currentResourceID.
548: ':parts'}=$partId;
549: } else {
550: $cache->{$currentSequence.':'.$currentResourceID.
551: ':parts'}.=':'.$partId;
552: }
553: $allkeys{$currentSequence.':'.$currentResourceID.
554: ':parts'}++;
555: }
556: if($beenHere{'r:'.$partId.':'.$responseId} == 0) {
557: $beenHere{'r:'.$partId.':'.$responseId}++;
558: if(!defined($cache->{$currentSequence.':'.
559: $currentResourceID.':'.$partId.
560: ':responseIDs'})) {
561: $cache->{$currentSequence.':'.$currentResourceID.
562: ':'.$partId.':responseIDs'}=$responseId;
563: } else {
564: $cache->{$currentSequence.':'.$currentResourceID.
565: ':'.$partId.':responseIDs'}.=':'.
566: $responseId;
567: }
568: $allkeys{$currentSequence.':'.$currentResourceID.':'.
569: $partId.':responseIDs'}++;
570: }
571: if(/^optionresponse/ &&
572: $beenHere{'o:'.$partId.':'.$currentResourceID} == 0) {
573: $beenHere{'o:'.$partId.$currentResourceID}++;
574: if(defined($cache->{'OptionResponses'})) {
575: $cache->{'OptionResponses'}.= ':::'.
576: $currentSequence.':'.$currentResourceID.':'.
577: $partId.':'.$responseId;
578: } else {
579: $cache->{'OptionResponses'}= $currentSequence.':'.
580: $currentResourceID.':'.
581: $partId.':'.$responseId;
582: }
583: $allkeys{'OptionResponses'}++;
584: }
585: }
586: }
587: }
588:
589: # if resource == finish resource, then it is the end of a sequence/page
590: if($currentResourceID eq $lastResourceID) {
591: # pop off last resource of sequence
592: $currentResourceID=pop(@currentResource);
593: $lastResourceID=pop(@finishResource);
594:
595: if(defined($cache->{$currentSequence.':problems'})) {
596: # Capture sequence information here
597: $cache->{$currentSequence.':title'}=
598: $hash{'title_'.$currentResourceID};
599: $allkeys{$currentSequence.':title'}++;
600: $cache->{$currentSequence.':source'}=
601: $hash{'src_'.$currentResourceID};
602: $allkeys{$currentSequence.':source'}++;
603:
604: my $totalProblems=0;
605: foreach my $currentProblem (split(/\:/,
606: $cache->{$currentSequence.
607: ':problems'})) {
608: foreach (split(/\:/,$cache->{$currentSequence.':'.
609: $currentProblem.
610: ':parts'})) {
611: $totalProblems++;
612: }
613: }
614: my @titleLength=split(//,$cache->{$currentSequence.
615: ':title'});
616: # $extra is 5 for problems correct and 3 for space
617: # between problems correct and problem output
618: my $extra = 8;
619: if(($totalProblems + $extra) > (scalar @titleLength)) {
620: $cache->{$currentSequence.':columnWidth'}=
621: $totalProblems + $extra;
622: } else {
623: $cache->{$currentSequence.':columnWidth'}=
624: (scalar @titleLength);
625: }
626: $allkeys{$currentSequence.':columnWidth'}++;
627: } else {
628: # Remove sequence from list, if it contains no problems to
629: # display.
630: $cache->{'orderedSequences'}=~s/$currentSequence//;
631: $cache->{'orderedSequences'}=~s/::/:/g;
632: $cache->{'orderedSequences'}=~s/^:|:$//g;
633: }
634:
635: $currentSequence=pop(@sequences);
636: if($currentSequence eq $topLevelSequenceNumber) {
637: last;
638: }
639: }
640:
641: # MOVE!!!
642: # move to next resource
643: unless(defined($hash{'to_'.$currentResourceID})) {
644: # big problem, need to handle. Next is probably wrong
645: my $errorMessage = 'Big problem in ';
646: $errorMessage .= 'loncoursedata::ProcessTopLevelMap.';
647: $errorMessage .= " bighash to_$currentResourceID not defined!";
648: &Apache::lonnet::logthis($errorMessage);
649: if (!defined($currentResourceID)) {last;}
650: }
651: my @nextResources=();
652: foreach (split(/\,/,$hash{'to_'.$currentResourceID})) {
653: if(!defined($sequenceRecord{$currentSequence.':'.
654: $hash{'goesto_'.$_}})) {
655: push(@nextResources, $hash{'goesto_'.$_});
656: }
657: }
658: push(@currentResource, @nextResources);
659: # Set the next resource to be processed
660: $currentResourceID=pop(@currentResource);
661: }
662:
663: my @theKeys = keys(%allkeys);
664: my $newkeys = join(':::', @theKeys);
665: $cache->{'ResourceKeys'} = join(':::', $newkeys);
666: if($newkeys ne $oldkeys) {
667: $cache->{'ResourceUpdated'} = 'true';
668: } else {
669: $cache->{'ResourceUpdated'} = 'false';
670: }
671:
672: unless (untie(%hash)) {
673: &Apache::lonnet::logthis("<font color=blue>WARNING: ".
674: "Could not untie coursemap $fn (browse)".
675: ".</font>");
676: }
677:
678: return 'OK';
679: }
680:
681: =pod
682:
683: =item &ProcessClasslist()
684:
685: Taking the class list dumped from &DownloadClasslist(), all the
686: students and their non-class information is processed using the
687: &ProcessStudentInformation() function. A date stamp is also recorded for
688: when the data was processed.
689:
690: Takes data downloaded for a student and breaks it up into managable pieces and
691: stored in cache data. The username, domain, class related date, PID,
692: full name, and section are all processed here.
693:
694: =over 4
695:
696: Input: $cache, $classlist, $courseID, $ChartDB, $c
697:
698: $cache: A hash pointer to store the data
699:
700: $classlist: The hash of data collected about a student from
701: &DownloadClasslist(). The hash contains a list of students, a pointer
702: to a hash of student information for each student, and each students section
703: number.
704:
705: $courseID: The course ID
706:
707: $ChartDB: The name of the cache database file.
708:
709: $c: The connection class used to determine if an abort has been sent to the
710: browser
711:
712: Output: @names
713:
714: @names: An array of students whose information has been processed, and are to
715: be considered in an arbitrary order. The entries in @names are of the form
716: username:domain.
717:
718: The values in $cache are as follows:
719:
720: *NOTE: for the following $name implies username:domain
721: $name.':error' only defined if an error occured. Value
722: contains the error message
723: $name.':lastDownloadTime' unconverted time of the last update of a
724: student\'s course data
725: $name.'updateTime' coverted time of the last update of a
726: student\'s course data
727: $name.':username' username of a student
728: $name.':domain' domain of a student
729: $name.':fullname' full name of a student
730: $name.':id' PID of a student
731: $name.':Status' active/expired status of a student
732: $name.':section' section of a student
733:
734: =back
735:
736: =cut
737:
738: sub ProcessClasslist {
739: my ($cache,$classlist,$courseID,$c)=@_;
740: my @names=();
741:
742: $cache->{'ClasslistTimeStamp'}=$classlist->{'lastDownloadTime'};
743: if($classlist->{'UpToDate'} eq 'true') {
744: return split(/:::/,$cache->{'NamesOfStudents'});;
745: }
746:
747: foreach my $name (keys(%$classlist)) {
748: if($name =~ /\:section/ || $name =~ /\:studentInformation/ ||
749: $name eq '' || $name eq 'UpToDate' || $name eq 'lastDownloadTime') {
750: next;
751: }
752: if($c->aborted()) {
753: return ();
754: }
755: my $studentInformation = $classlist->{$name.':studentInformation'};
756: my $date = $classlist->{$name};
757: my ($studentName,$studentDomain) = split(/\:/,$name);
758:
759: $cache->{$name.':username'}=$studentName;
760: $cache->{$name.':domain'}=$studentDomain;
761: # Initialize timestamp for student
762: if(!defined($cache->{$name.':lastDownloadTime'})) {
763: $cache->{$name.':lastDownloadTime'}='Not downloaded';
764: $cache->{$name.':updateTime'}=' Not updated';
765: }
766:
767: my $error = 0;
768: foreach(keys(%$studentInformation)) {
769: if(/^(con_lost|error|no_such_host)/i) {
770: $cache->{$name.':error'}=
771: 'Could not download student environment data.';
772: $cache->{$name.':fullname'}='';
773: $cache->{$name.':id'}='';
774: $error = 1;
775: }
776: }
777: next if($error);
778: push(@names,$name);
779: $cache->{$name.':fullname'}=&ProcessFullName(
780: $studentInformation->{'lastname'},
781: $studentInformation->{'generation'},
782: $studentInformation->{'firstname'},
783: $studentInformation->{'middlename'});
784: $cache->{$name.':id'}=$studentInformation->{'id'};
785:
786: my ($end, $start)=split(':',$date);
787: $courseID=~s/\_/\//g;
788: $courseID=~s/^(\w)/\/$1/;
789:
790: my $sec='';
791: my $sectionData = $classlist->{$name.':sections'};
792: foreach my $key (keys (%$sectionData)) {
793: my $value = $sectionData->{$key};
794: if ($key=~/^$courseID(?:\/)*(\w+)*\_st$/) {
795: my $tempsection=$1;
796: if($key eq $courseID.'_st') {
797: $tempsection='';
798: }
799: my (undef,$roleend,$rolestart)=split(/\_/,$value);
800: if($roleend eq $end && $rolestart eq $start) {
801: $sec = $tempsection;
802: last;
803: }
804: }
805: }
806:
807: my $status='Expired';
808: if(((!$end) || time < $end) && ((!$start) || (time > $start))) {
809: $status='Active';
810: }
811: $cache->{$name.':Status'}=$status;
812: $cache->{$name.':section'}=$sec;
813:
814: if($sec eq '' || !defined($sec) || $sec eq ' ') {
815: $sec = 'none';
816: }
817: if(defined($cache->{'sectionList'})) {
818: if($cache->{'sectionList'} !~ /(^$sec:|^$sec$|:$sec$|:$sec:)/) {
819: $cache->{'sectionList'} .= ':'.$sec;
820: }
821: } else {
822: $cache->{'sectionList'} = $sec;
823: }
824: }
825:
826: $cache->{'ClasslistTimestamp'}=time;
827: $cache->{'NamesOfStudents'}=join(':::',@names);
828:
829: return @names;
830: }
831:
832: =pod
833:
834: =item &ProcessStudentData()
835:
836: Takes the course data downloaded for a student in
837: &DownloadCourseInformation() and breaks it up into key value pairs
838: to be stored in the cached data. The keys are comprised of the
839: $username:$domain:$keyFromCourseDatabase. The student username:domain is
840: stored away signifying that the students information has been downloaded and
841: can be reused from cached data.
842:
843: =over 4
844:
845: Input: $cache, $courseData, $name
846:
847: $cache: A hash pointer to store data
848:
849: $courseData: A hash pointer that points to the course data downloaded for a
850: student.
851:
852: $name: username:domain
853:
854: Output: None
855:
856: *NOTE: There is no output, but an error message is stored away in the cache
857: data. This is checked in &FormatStudentData(). The key username:domain:error
858: will only exist if an error occured. The error is an error from
859: &DownloadCourseInformation().
860:
861: =back
862:
863: =cut
864:
865: sub ProcessStudentData {
866: my ($cache,$courseData,$name)=@_;
867:
868: if(!&CheckDateStampError($courseData, $cache, $name)) {
869: return;
870: }
871:
872: # This little delete thing, should not be here. Move some other
873: # time though.
874: if(defined($cache->{$name.':keys'})) {
875: foreach (split(':::', $cache->{$name.':keys'})) {
876: delete $cache->{$name.':'.$_};
877: }
878: delete $cache->{$name.':keys'};
879: }
880:
881: my %courseKeys;
882: # user name:domain was prepended earlier in DownloadCourseInformation
883: foreach (keys %$courseData) {
884: my $currentKey = $_;
885: $currentKey =~ s/^$name//;
886: $courseKeys{$currentKey}++;
887: $cache->{$_}=$courseData->{$_};
888: }
889:
890: $cache->{$name.':keys'} = join(':::', keys(%courseKeys));
891:
892: return;
893: }
894:
895: =pod
896:
897: =item &ExtractStudentData()
898:
899: HISTORY: This function originally existed in every statistics module,
900: and performed different tasks, the had some overlap. Due to the need
901: for the data from the different modules, they were combined into
902: a single function.
903:
904: This function now extracts all the necessary course data for a student
905: from what was downloaded from their homeserver. There is some extra
906: time overhead compared to the ProcessStudentInformation function, but
907: it would have had to occurred at some point anyways. This is now
908: typically called while downloading the data it will process. It is
909: the brother function to ProcessStudentInformation.
910:
911: =over 4
912:
913: Input: $input, $output, $data, $name
914:
915: $input: A hash that contains the input data to be processed
916:
917: $output: A hash to contain the processed data
918:
919: $data: A hash containing the information on what is to be
920: processed and how (basically).
921:
922: $name: username:domain
923:
924: The input is slightly different here, but is quite simple.
925: It is currently used where the $input, $output, and $data
926: can and are often the same hashes, but they do not need
927: to be.
928:
929: Output: None
930:
931: *NOTE: There is no output, but an error message is stored away in the cache
932: data. This is checked in &FormatStudentData(). The key username:domain:error
933: will only exist if an error occured. The error is an error from
934: &DownloadCourseInformation().
935:
936: =back
937:
938: =cut
939:
940: sub ExtractStudentData {
941: my ($input, $output, $data, $name)=@_;
942:
943: if(!&CheckDateStampError($input, $data, $name)) {
944: return;
945: }
946:
947: # This little delete thing, should not be here. Move some other
948: # time though.
949: my %allkeys;
950: if(defined($output->{$name.':keys'})) {
951: foreach (split(':::', $output->{$name.':keys'})) {
952: delete $output->{$name.':'.$_};
953: }
954: delete $output->{$name.':keys'};
955: }
956:
957: my ($username,$domain)=split(':',$name);
958:
959: my $Version;
960: my $problemsCorrect = 0;
961: my $totalProblems = 0;
962: my $problemsSolved = 0;
963: my $numberOfParts = 0;
964: my $totalAwarded = 0;
965: foreach my $sequence (split(':', $data->{'orderedSequences'})) {
966: foreach my $problemID (split(':', $data->{$sequence.':problems'})) {
967: my $problem = $data->{$problemID.':problem'};
968: my $LatestVersion = $input->{$name.':version:'.$problem};
969:
970: # Output dashes for all the parts of this problem if there
971: # is no version information about the current problem.
972: $output->{$name.':'.$problemID.':NoVersion'} = 'false';
973: $allkeys{$name.':'.$problemID.':NoVersion'}++;
974: if(!$LatestVersion) {
975: foreach my $part (split(/\:/,$data->{$sequence.':'.
976: $problemID.
977: ':parts'})) {
978: $output->{$name.':'.$problemID.':'.$part.':tries'} = 0;
979: $output->{$name.':'.$problemID.':'.$part.':awarded'} = 0;
980: $output->{$name.':'.$problemID.':'.$part.':code'} = ' ';
981: $allkeys{$name.':'.$problemID.':'.$part.':tries'}++;
982: $allkeys{$name.':'.$problemID.':'.$part.':awarded'}++;
983: $allkeys{$name.':'.$problemID.':'.$part.':code'}++;
984: $totalProblems++;
985: }
986: $output->{$name.':'.$problemID.':NoVersion'} = 'true';
987: next;
988: }
989:
990: my %partData=undef;
991: # Initialize part data, display skips correctly
992: # Skip refers to when a student made no submissions on that
993: # part/problem.
994: foreach my $part (split(/\:/,$data->{$sequence.':'.
995: $problemID.
996: ':parts'})) {
997: $partData{$part.':tries'}=0;
998: $partData{$part.':code'}=' ';
999: $partData{$part.':awarded'}=0;
1000: $partData{$part.':timestamp'}=0;
1001: foreach my $response (split(':', $data->{$sequence.':'.
1002: $problemID.':'.
1003: $part.':responseIDs'})) {
1004: $partData{$part.':'.$response.':submission'}='';
1005: }
1006: }
1007:
1008: # Looping through all the versions of each part, starting with the
1009: # oldest version. Basically, it gets the most recent
1010: # set of grade data for each part.
1011: my @submissions = ();
1012: for(my $Version=1; $Version<=$LatestVersion; $Version++) {
1013: foreach my $part (split(/\:/,$data->{$sequence.':'.
1014: $problemID.
1015: ':parts'})) {
1016:
1017: if(!defined($input->{"$name:$Version:$problem".
1018: ":resource.$part.solved"})) {
1019: # No grade for this submission, so skip
1020: next;
1021: }
1022:
1023: my $tries=0;
1024: my $code=' ';
1025: my $awarded=0;
1026:
1027: $tries = $input->{$name.':'.$Version.':'.$problem.
1028: ':resource.'.$part.'.tries'};
1029: $awarded = $input->{$name.':'.$Version.':'.$problem.
1030: ':resource.'.$part.'.awarded'};
1031:
1032: $partData{$part.':awarded'}=($awarded) ? $awarded : 0;
1033: $partData{$part.':tries'}=($tries) ? $tries : 0;
1034:
1035: $partData{$part.':timestamp'}=$input->{$name.':'.$Version.':'.
1036: $problem.
1037: ':timestamp'};
1038: if(!$input->{$name.':'.$Version.':'.$problem.':resource.'.$part.
1039: '.previous'}) {
1040: foreach my $response (split(':',
1041: $data->{$sequence.':'.
1042: $problemID.':'.
1043: $part.':responseIDs'})) {
1044: @submissions=($input->{$name.':'.$Version.':'.
1045: $problem.
1046: ':resource.'.$part.'.'.
1047: $response.'.submission'},
1048: @submissions);
1049: }
1050: }
1051:
1052: my $val = $input->{$name.':'.$Version.':'.$problem.
1053: ':resource.'.$part.'.solved'};
1054: if ($val eq 'correct_by_student') {$code = '*';}
1055: elsif ($val eq 'correct_by_override') {$code = '+';}
1056: elsif ($val eq 'incorrect_attempted') {$code = '.';}
1057: elsif ($val eq 'incorrect_by_override'){$code = '-';}
1058: elsif ($val eq 'excused') {$code = 'x';}
1059: elsif ($val eq 'ungraded_attempted') {$code = '#';}
1060: else {$code = ' ';}
1061: $partData{$part.':code'}=$code;
1062: }
1063: }
1064:
1065: foreach my $part (split(/\:/,$data->{$sequence.':'.$problemID.
1066: ':parts'})) {
1067: $output->{$name.':'.$problemID.':'.$part.':wrong'} =
1068: $partData{$part.':tries'};
1069: $allkeys{$name.':'.$problemID.':'.$part.':wrong'}++;
1070:
1071: if($partData{$part.':code'} eq '*') {
1072: $output->{$name.':'.$problemID.':'.$part.':wrong'}--;
1073: $problemsCorrect++;
1074: } elsif($partData{$part.':code'} eq '+') {
1075: $output->{$name.':'.$problemID.':'.$part.':wrong'}--;
1076: $problemsCorrect++;
1077: }
1078:
1079: $output->{$name.':'.$problemID.':'.$part.':tries'} =
1080: $partData{$part.':tries'};
1081: $output->{$name.':'.$problemID.':'.$part.':code'} =
1082: $partData{$part.':code'};
1083: $output->{$name.':'.$problemID.':'.$part.':awarded'} =
1084: $partData{$part.':awarded'};
1085: $allkeys{$name.':'.$problemID.':'.$part.':tries'}++;
1086: $allkeys{$name.':'.$problemID.':'.$part.':code'}++;
1087: $allkeys{$name.':'.$problemID.':'.$part.':awarded'}++;
1088:
1089: $totalAwarded += $partData{$part.':awarded'};
1090: $output->{$name.':'.$problemID.':'.$part.':timestamp'} =
1091: $partData{$part.':timestamp'};
1092: $allkeys{$name.':'.$problemID.':'.$part.':timestamp'}++;
1093:
1094: foreach my $response (split(':', $data->{$sequence.':'.
1095: $problemID.':'.
1096: $part.':responseIDs'})) {
1097: $output->{$name.':'.$problemID.':'.$part.':'.$response.
1098: ':submission'}=join(':::',@submissions);
1099: $allkeys{$name.':'.$problemID.':'.$part.':'.$response.
1100: ':submission'}++;
1101: }
1102:
1103: if($partData{$part.':code'} ne 'x') {
1104: $totalProblems++;
1105: }
1106: }
1107: }
1108:
1109: $output->{$name.':'.$sequence.':problemsCorrect'} = $problemsCorrect;
1110: $allkeys{$name.':'.$sequence.':problemsCorrect'}++;
1111: $problemsSolved += $problemsCorrect;
1112: $problemsCorrect=0;
1113: }
1114:
1115: $output->{$name.':problemsSolved'} = $problemsSolved;
1116: $output->{$name.':totalProblems'} = $totalProblems;
1117: $output->{$name.':totalAwarded'} = $totalAwarded;
1118: $allkeys{$name.':problemsSolved'}++;
1119: $allkeys{$name.':totalProblems'}++;
1120: $allkeys{$name.':totalAwarded'}++;
1121:
1122: $output->{$name.':keys'} = join(':::', keys(%allkeys));
1123:
1124: return;
1125: }
1126:
1127: sub LoadDiscussion {
1128: my ($courseID)=@_;
1129: my %Discuss=();
1130: my %contrib=&Apache::lonnet::dump(
1131: $courseID,
1132: $ENV{'course.'.$courseID.'.domain'},
1133: $ENV{'course.'.$courseID.'.num'});
1134:
1135: #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
1136:
1137: foreach my $temp(keys %contrib) {
1138: if ($temp=~/^version/) {
1139: my $ver=$contrib{$temp};
1140: my ($dummy,$prb)=split(':',$temp);
1141: for (my $idx=1; $idx<=$ver; $idx++ ) {
1142: my $name=$contrib{"$idx:$prb:sendername"};
1143: $Discuss{"$name:$prb"}=$idx;
1144: }
1145: }
1146: }
1147:
1148: return \%Discuss;
1149: }
1150:
1151: # ----- END PROCESSING FUNCTIONS ---------------------------------------
1152:
1153: =pod
1154:
1155: =head1 HELPER FUNCTIONS
1156:
1157: These are just a couple of functions do various odd and end
1158: jobs. There was also a couple of bulk functions added. These are
1159: &DownloadStudentCourseData(), &DownloadStudentCourseDataSeparate(), and
1160: &CheckForResidualDownload(). These functions now act as the interface
1161: for downloading student course data. The statistical modules should
1162: no longer make the calls to dump and download and process etc. They
1163: make calls to these bulk functions to get their data.
1164:
1165: =cut
1166:
1167: # ----- HELPER FUNCTIONS -----------------------------------------------
1168:
1169: sub CheckDateStampError {
1170: my ($courseData, $cache, $name)=@_;
1171: if($courseData->{$name.':UpToDate'} eq 'true') {
1172: $cache->{$name.':lastDownloadTime'} =
1173: $courseData->{$name.':lastDownloadTime'};
1174: if($courseData->{$name.':lastDownloadTime'} eq 'Not downloaded') {
1175: $cache->{$name.':updateTime'} = ' Not updated';
1176: } else {
1177: $cache->{$name.':updateTime'}=
1178: localtime($courseData->{$name.':lastDownloadTime'});
1179: }
1180: return 0;
1181: }
1182:
1183: $cache->{$name.':lastDownloadTime'}=$courseData->{$name.':lastDownloadTime'};
1184: if($courseData->{$name.':lastDownloadTime'} eq 'Not downloaded') {
1185: $cache->{$name.':updateTime'} = ' Not updated';
1186: } else {
1187: $cache->{$name.':updateTime'}=
1188: localtime($courseData->{$name.':lastDownloadTime'});
1189: }
1190:
1191: if(defined($courseData->{$name.':error'})) {
1192: $cache->{$name.':error'}=$courseData->{$name.':error'};
1193: return 0;
1194: }
1195:
1196: return 1;
1197: }
1198:
1199: =pod
1200:
1201: =item &ProcessFullName()
1202:
1203: Takes lastname, generation, firstname, and middlename (or some partial
1204: set of this data) and returns the full name version as a string. Format
1205: is Lastname generation, firstname middlename or a subset of this.
1206:
1207: =cut
1208:
1209: sub ProcessFullName {
1210: my ($lastname, $generation, $firstname, $middlename)=@_;
1211: my $Str = '';
1212:
1213: # Strip whitespace preceeding & following name components.
1214: $lastname =~ s/(\s+$|^\s+)//g;
1215: $generation =~ s/(\s+$|^\s+)//g;
1216: $firstname =~ s/(\s+$|^\s+)//g;
1217: $middlename =~ s/(\s+$|^\s+)//g;
1218:
1219: if($lastname ne '') {
1220: $Str .= $lastname;
1221: $Str .= ' '.$generation if ($generation ne '');
1222: $Str .= ',';
1223: $Str .= ' '.$firstname if ($firstname ne '');
1224: $Str .= ' '.$middlename if ($middlename ne '');
1225: } else {
1226: $Str .= $firstname if ($firstname ne '');
1227: $Str .= ' '.$middlename if ($middlename ne '');
1228: $Str .= ' '.$generation if ($generation ne '');
1229: }
1230:
1231: return $Str;
1232: }
1233:
1234: =pod
1235:
1236: =item &TestCacheData()
1237:
1238: Determine if the cache database can be accessed with a tie. It waits up to
1239: ten seconds before returning failure. This function exists to help with
1240: the problems with stopping the data download. When an abort occurs and the
1241: user quickly presses a form button and httpd child is created. This
1242: child needs to wait for the other to finish (hopefully within ten seconds).
1243:
1244: =over 4
1245:
1246: Input: $ChartDB
1247:
1248: $ChartDB: The name of the cache database to be opened
1249:
1250: Output: -1, 0, 1
1251:
1252: -1: Could not tie database
1253: 0: Use cached data
1254: 1: New cache database created, use that.
1255:
1256: =back
1257:
1258: =cut
1259:
1260: sub TestCacheData {
1261: my ($ChartDB,$isRecalculate,$totalDelay)=@_;
1262: my $isCached=-1;
1263: my %testData;
1264: my $tieTries=0;
1265:
1266: if(!defined($totalDelay)) {
1267: $totalDelay = 10;
1268: }
1269:
1270: if ((-e "$ChartDB") && (!$isRecalculate)) {
1271: $isCached = 1;
1272: } else {
1273: $isCached = 0;
1274: }
1275:
1276: while($tieTries < $totalDelay) {
1277: my $result=0;
1278: if($isCached) {
1279: $result=tie(%testData,'GDBM_File',$ChartDB,&GDBM_READER(),0640);
1280: } else {
1281: $result=tie(%testData,'GDBM_File',$ChartDB,&GDBM_NEWDB(),0640);
1282: }
1283: if($result) {
1284: last;
1285: }
1286: $tieTries++;
1287: sleep 1;
1288: }
1289: if($tieTries >= $totalDelay) {
1290: return -1;
1291: }
1292:
1293: untie(%testData);
1294:
1295: return $isCached;
1296: }
1297:
1298: sub DownloadStudentCourseData {
1299: my ($students,$checkDate,$cacheDB,$extract,$status,$courseID,$r,$c)=@_;
1300:
1301: my $title = 'LON-CAPA Statistics';
1302: my $heading = 'Download and Process Course Data';
1303: my $studentCount = scalar(@$students);
1304:
1305: my $WhatIWant;
1306: $WhatIWant = '(^version:|';
1307: $WhatIWant .= '^\d+:.+?:(resource\.\d+\.';
1308: $WhatIWant .= '(solved|tries|previous|awarded|(\d+\.submission))\s*$';#'
1309: $WhatIWant .= '|timestamp)';
1310: $WhatIWant .= ')';
1311: # $WhatIWant = '.';
1312:
1313: my %prog_state;
1314: if($status eq 'true') {
1315: %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r, $title,
1316: $heading,($#$students)+1);
1317: }
1318:
1319: foreach (@$students) {
1320: my %cache;
1321:
1322: if($c->aborted()) { return 'Aborted'; }
1323:
1324: if($status eq 'true') {
1325: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
1326: 'last student '.$_);
1327: }
1328:
1329: my $downloadTime='Not downloaded';
1330: my $needUpdate = 'false';
1331: if($checkDate eq 'true' &&
1332: tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER(),0640)) {
1333: $downloadTime = $cache{$_.':lastDownloadTime'};
1334: $needUpdate = $cache{'ResourceUpdated'};
1335: untie(%cache);
1336: }
1337:
1338: if($c->aborted()) { return 'Aborted'; }
1339:
1340: if($needUpdate eq 'true') {
1341: $downloadTime = 'Not downloaded';
1342: }
1343: my $courseData =
1344: &DownloadCourseInformation($_, $courseID, $downloadTime,
1345: $WhatIWant);
1346: if(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT(),0640)) {
1347: foreach my $key (keys(%$courseData)) {
1348: if($key =~ /^(con_lost|error|no_such_host)/i) {
1349: $courseData->{$_.':error'} = 'No course data for '.$_;
1350: last;
1351: }
1352: }
1353: if($extract eq 'true') {
1354: &ExtractStudentData($courseData, \%cache, \%cache, $_);
1355: } else {
1356: &ProcessStudentData(\%cache, $courseData, $_);
1357: }
1358: untie(%cache);
1359: } else {
1360: next;
1361: }
1362: }
1363: if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state); }
1364:
1365: return 'OK';
1366: }
1367:
1368: sub DownloadStudentCourseDataSeparate {
1369: my ($students,$checkDate,$cacheDB,$extract,$status,$courseID,$r,$c)=@_;
1370: my $residualFile = $Apache::lonnet::tmpdir.$courseID.'DownloadFile.db';
1371: my $title = 'LON-CAPA Statistics';
1372: my $heading = 'Download Course Data';
1373:
1374: my $WhatIWant;
1375: $WhatIWant = '(^version:|';
1376: $WhatIWant .= '^\d+:.+?:(resource\.\d+\.';
1377: $WhatIWant .= '(solved|tries|previous|awarded|(\d+\.submission))\s*$';#'
1378: $WhatIWant .= '|timestamp)';
1379: $WhatIWant .= ')';
1380:
1381: &CheckForResidualDownload($cacheDB, 'true', 'true', $courseID, $r, $c);
1382:
1383: my $studentCount = scalar(@$students);
1384: my %prog_state;
1385: if($status eq 'true') {
1386: %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r, $title,
1387: $heading,($#$students)+1);
1388: }
1389: my $displayString='';
1390: foreach (@$students) {
1391: if($c->aborted()) {
1392: return 'Aborted';
1393: }
1394:
1395: if($status eq 'true') {
1396: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
1397: 'last student '.$_);
1398: }
1399:
1400: my %cache;
1401: my $downloadTime='Not downloaded';
1402: my $needUpdate = 'false';
1403: if($checkDate eq 'true' &&
1404: tie(%cache,'GDBM_File',$cacheDB,&GDBM_READER(),0640)) {
1405: $downloadTime = $cache{$_.':lastDownloadTime'};
1406: $needUpdate = $cache{'ResourceUpdated'};
1407: untie(%cache);
1408: }
1409:
1410: if($c->aborted()) {
1411: return 'Aborted';
1412: }
1413:
1414: if($needUpdate eq 'true') {
1415: $downloadTime = 'Not downloaded';
1416: }
1417:
1418: my $error = 0;
1419: my $courseData =
1420: &DownloadCourseInformation($_, $courseID, $downloadTime,
1421: $WhatIWant);
1422: my %downloadData;
1423: unless(tie(%downloadData,'GDBM_File',$residualFile,
1424: &GDBM_WRCREAT(),0640)) {
1425: return 'Failed to tie temporary download hash.';
1426: }
1427: foreach my $key (keys(%$courseData)) {
1428: $downloadData{$key} = $courseData->{$key};
1429: if($key =~ /^(con_lost|error|no_such_host)/i) {
1430: $error = 1;
1431: last;
1432: }
1433: }
1434: if($error) {
1435: foreach my $deleteKey (keys(%$courseData)) {
1436: delete $downloadData{$deleteKey};
1437: }
1438: $downloadData{$_.':error'} = 'No course data for '.$_;
1439: }
1440: untie(%downloadData);
1441: }
1442: if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r,
1443: \%prog_state); }
1444:
1445: return &CheckForResidualDownload($cacheDB, 'true', 'true',
1446: $courseID, $r, $c);
1447: }
1448:
1449: sub CheckForResidualDownload {
1450: my ($cacheDB,$extract,$status,$courseID,$r,$c)=@_;
1451:
1452: my $residualFile = $Apache::lonnet::tmpdir.$courseID.'DownloadFile.db';
1453: if(!-e $residualFile) {
1454: return 'OK';
1455: }
1456:
1457: my %downloadData;
1458: my %cache;
1459: unless(tie(%downloadData,'GDBM_File',$residualFile,&GDBM_READER(),0640)) {
1460: return 'Can not tie database for check for residual download: tempDB';
1461: }
1462: unless(tie(%cache,'GDBM_File',$cacheDB,&GDBM_WRCREAT(),0640)) {
1463: untie(%downloadData);
1464: return 'Can not tie database for check for residual download: cacheDB';
1465: }
1466:
1467: my @students=();
1468: my %checkStudent;
1469: my $key;
1470: while(($key, undef) = each %downloadData) {
1471: my @temp = split(':', $key);
1472: my $student = $temp[0].':'.$temp[1];
1473: if(!defined($checkStudent{$student})) {
1474: $checkStudent{$student}++;
1475: push(@students, $student);
1476: }
1477: }
1478:
1479: my $heading = 'Process Course Data';
1480: my $title = 'LON-CAPA Statistics';
1481: my $studentCount = scalar(@students);
1482: my %prog_state;
1483: if($status eq 'true') {
1484: %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r, $title,
1485: $heading,$#students+1);
1486: }
1487:
1488: my $count=1;
1489: foreach my $name (@students) {
1490: last if($c->aborted());
1491:
1492: if($status eq 'true') {
1493: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
1494: 'last student '.$name);
1495: }
1496:
1497: if($extract eq 'true') {
1498: &ExtractStudentData(\%downloadData, \%cache, \%cache, $name);
1499: } else {
1500: &ProcessStudentData(\%cache, \%downloadData, $name);
1501: }
1502: $count++;
1503: }
1504:
1505: if($status eq 'true') { &Apache::lonhtmlcommon::Close_PrgWin($r,
1506: \%prog_state); }
1507:
1508: untie(%cache);
1509: untie(%downloadData);
1510:
1511: if(!$c->aborted()) {
1512: my @files = ($residualFile);
1513: unlink(@files);
1514: }
1515:
1516: return 'OK';
1517: }
1518:
1519:
1520: ################################################
1521: ################################################
1522:
1523: =pod
1524:
1525: =item &make_into_hash($values);
1526:
1527: Returns a reference to a hash as described by $values. $values is
1528: assumed to be the result of
1529: join(':',map {&Apache::lonnet::escape($_)} %orighash);
1530:
1531: This is a helper function for get_current_state.
1532:
1533: =cut
1534:
1535: ################################################
1536: ################################################
1537: sub make_into_hash {
1538: my $values = shift;
1539: my %tmp = map { &Apache::lonnet::unescape($_); }
1540: split(':',$values);
1541: return \%tmp;
1542: }
1543:
1544:
1545: ################################################
1546: ################################################
1547:
1548: =pod
1549:
1550: =head1 LOCAL DATA CACHING SUBROUTINES
1551:
1552: The local caching is done using MySQL. There is no fall-back implementation
1553: if MySQL is not running.
1554:
1555: The programmers interface is to call &get_current_state() or some other
1556: primary interface subroutine (described below). The internals of this
1557: storage system are documented here.
1558:
1559: There are six tables used to store student performance data (the results of
1560: a dumpcurrent). Each of these tables is created in MySQL with a name of
1561: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate
1562: for the table. The tables and their purposes are described below.
1563:
1564: Some notes before we get started.
1565:
1566: Each table must have a PRIMARY KEY, which is a column or set of columns which
1567: will serve to uniquely identify a row of data. NULL is not allowed!
1568:
1569: INDEXes work best on integer data.
1570:
1571: JOIN is used to combine data from many tables into one output.
1572:
1573: lonmysql.pm is used for some of the interface, specifically the table creation
1574: calls. The inserts are done in bulk by directly calling the database handler.
1575: The SELECT ... JOIN statement used to retrieve the data does not have an
1576: interface in lonmysql.pm and I shudder at the thought of writing one.
1577:
1578: =head3 Table Descriptions
1579:
1580: =over 4
1581:
1582: =item $symb_table
1583:
1584: The symb_table has two columns. The first is a 'symb_id' and the second
1585: is the text name for the 'symb' (limited to 64k). The 'symb_id' is generated
1586: automatically by MySQL so inserts should be done on this table with an
1587: empty first element. This table has its PRIMARY KEY on the 'symb_id'.
1588:
1589: =item $part_table
1590:
1591: The part_table has two columns. The first is a 'part_id' and the second
1592: is the text name for the 'part' (limited to 100 characters). The 'part_id' is
1593: generated automatically by MySQL so inserts should be done on this table with
1594: an empty first element. This table has its PRIMARY KEY on the 'part' (100
1595: characters) and a KEY on 'part_id'.
1596:
1597: =item $student_table
1598:
1599: The student_table has two columns. The first is a 'student_id' and the second
1600: is the text description of the 'student' (typically username:domain) (less
1601: than 100 characters). The 'student_id' is automatically generated by MySQL.
1602: The use of the name 'student_id' is loaded, I know, but this ID is used ONLY
1603: internally to the MySQL database and is not the same as the students ID
1604: (stored in the students environment). This table has its PRIMARY KEY on the
1605: 'student' (100 characters).
1606:
1607: =item $updatetime_table
1608:
1609: The updatetime_table has two columns. The first is 'student' (100 characters,
1610: typically username:domain). The second is 'updatetime', which is an unsigned
1611: integer, NOT a MySQL date. This table has its PRIMARY KEY on 'student' (100
1612: characters).
1613:
1614: =item $performance_table
1615:
1616: The performance_table has 9 columns. The first three are 'symb_id',
1617: 'student_id', and 'part_id'. These comprise the PRIMARY KEY for this table
1618: and are directly related to the $symb_table, $student_table, and $part_table
1619: described above. MySQL does better indexing on numeric items than text,
1620: so we use these three "index tables". The remaining columns are
1621: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
1622: These are either the MySQL type TINYTEXT or various integers ('tries' and
1623: 'timestamp'). This table has KEYs of 'student_id' and 'symb_id'.
1624: For use of this table, see the functions described below.
1625:
1626: =item $parameters_table
1627:
1628: The parameters_table holds the data that does not fit neatly into the
1629: performance_table. The parameters table has four columns: 'symb_id',
1630: 'student_id', 'parameter', and 'value'. 'symb_id', 'student_id', and
1631: 'parameter' comprise the PRIMARY KEY for this table. 'parameter' is
1632: limited to 255 characters. 'value' is limited to 64k characters.
1633:
1634: =back
1635:
1636: =head3 Important Subroutines
1637:
1638: Here is a brief overview of the subroutines which are likely to be of
1639: interest:
1640:
1641: =over 4
1642:
1643: =item &get_current_state(): programmers interface.
1644:
1645: =item &init_dbs(): table creation
1646:
1647: =item &update_student_data(): data storage calls
1648:
1649: =item &get_student_data_from_performance_cache(): data retrieval
1650:
1651: =back
1652:
1653: =head3 Main Documentation
1654:
1655: =over 4
1656:
1657: =cut
1658:
1659: ################################################
1660: ################################################
1661:
1662: ################################################
1663: ################################################
1664: {
1665:
1666: my $current_course ='';
1667: my $symb_table;
1668: my $part_table;
1669: my $student_table;
1670: my $updatetime_table;
1671: my $performance_table;
1672: my $parameters_table;
1673:
1674: ################################################
1675: ################################################
1676:
1677: =pod
1678:
1679: =item &setup_table_names()
1680:
1681: input: course id
1682:
1683: output: none
1684:
1685: Sets the package variables for the MySQL table names:
1686:
1687: =over 4
1688:
1689: =item $symb_table
1690:
1691: =item $part_table
1692:
1693: =item $student_table
1694:
1695: =item $updatetime_table
1696:
1697: =item $performance_table
1698:
1699: =item $parameters_table
1700:
1701: =back
1702:
1703: =cut
1704:
1705: ################################################
1706: ################################################
1707: sub setup_table_names {
1708: my $courseid = shift;
1709: if (! defined($courseid)) {
1710: $courseid = $ENV{'request.course.id'};
1711: }
1712: #
1713: # Set up database names
1714: my $base_id = $courseid;
1715: $symb_table = $base_id.'_'.'symb';
1716: $part_table = $base_id.'_'.'part';
1717: $student_table = $base_id.'_'.'student';
1718: $updatetime_table = $base_id.'_'.'updatetime';
1719: $performance_table = $base_id.'_'.'performance';
1720: $parameters_table = $base_id.'_'.'parameters';
1721: return;
1722: }
1723:
1724: ################################################
1725: ################################################
1726:
1727: =pod
1728:
1729: =item &init_dbs()
1730:
1731: Input: course id
1732:
1733: Output: 0 on success, positive integer on error
1734:
1735: This routine issues the calls to lonmysql to create the tables used to
1736: store student data.
1737:
1738: =cut
1739:
1740: ################################################
1741: ################################################
1742: sub init_dbs {
1743: my $courseid = shift;
1744: &setup_table_names($courseid);
1745: #
1746: # Note - changes to this table must be reflected in the code that
1747: # stores the data (calls &Apache::lonmysql::store_row with this table
1748: # id
1749: my $symb_table_def = {
1750: id => $symb_table,
1751: permanent => 'no',
1752: columns => [{ name => 'symb_id',
1753: type => 'MEDIUMINT UNSIGNED',
1754: restrictions => 'NOT NULL',
1755: auto_inc => 'yes', },
1756: { name => 'symb',
1757: type => 'MEDIUMTEXT',
1758: restrictions => 'NOT NULL'},
1759: ],
1760: 'PRIMARY KEY' => ['symb_id'],
1761: };
1762: #
1763: my $part_table_def = {
1764: id => $part_table,
1765: permanent => 'no',
1766: columns => [{ name => 'part_id',
1767: type => 'MEDIUMINT UNSIGNED',
1768: restrictions => 'NOT NULL',
1769: auto_inc => 'yes', },
1770: { name => 'part',
1771: type => 'VARCHAR(100)',
1772: restrictions => 'NOT NULL'},
1773: ],
1774: 'PRIMARY KEY' => ['part (100)'],
1775: 'KEY' => [{ columns => ['part_id']},],
1776: };
1777: #
1778: my $student_table_def = {
1779: id => $student_table,
1780: permanent => 'no',
1781: columns => [{ name => 'student_id',
1782: type => 'MEDIUMINT UNSIGNED',
1783: restrictions => 'NOT NULL',
1784: auto_inc => 'yes', },
1785: { name => 'student',
1786: type => 'VARCHAR(100)',
1787: restrictions => 'NOT NULL'},
1788: ],
1789: 'PRIMARY KEY' => ['student (100)'],
1790: 'KEY' => [{ columns => ['student_id']},],
1791: };
1792: #
1793: my $updatetime_table_def = {
1794: id => $updatetime_table,
1795: permanent => 'no',
1796: columns => [{ name => 'student',
1797: type => 'VARCHAR(100)',
1798: restrictions => 'NOT NULL UNIQUE',},
1799: { name => 'updatetime',
1800: type => 'INT UNSIGNED',
1801: restrictions => 'NOT NULL' },
1802: ],
1803: 'PRIMARY KEY' => ['student (100)'],
1804: };
1805: #
1806: my $performance_table_def = {
1807: id => $performance_table,
1808: permanent => 'no',
1809: columns => [{ name => 'symb_id',
1810: type => 'MEDIUMINT UNSIGNED',
1811: restrictions => 'NOT NULL' },
1812: { name => 'student_id',
1813: type => 'MEDIUMINT UNSIGNED',
1814: restrictions => 'NOT NULL' },
1815: { name => 'part_id',
1816: type => 'MEDIUMINT UNSIGNED',
1817: restrictions => 'NOT NULL' },
1818: { name => 'solved',
1819: type => 'TINYTEXT' },
1820: { name => 'tries',
1821: type => 'SMALLINT UNSIGNED' },
1822: { name => 'awarded',
1823: type => 'TINYTEXT' },
1824: { name => 'award',
1825: type => 'TINYTEXT' },
1826: { name => 'awarddetail',
1827: type => 'TINYTEXT' },
1828: { name => 'timestamp',
1829: type => 'INT UNSIGNED'},
1830: ],
1831: 'PRIMARY KEY' => ['symb_id','student_id','part_id'],
1832: 'KEY' => [{ columns=>['student_id'] },
1833: { columns=>['symb_id'] },],
1834: };
1835: #
1836: my $parameters_table_def = {
1837: id => $parameters_table,
1838: permanent => 'no',
1839: columns => [{ name => 'symb_id',
1840: type => 'MEDIUMINT UNSIGNED',
1841: restrictions => 'NOT NULL' },
1842: { name => 'student_id',
1843: type => 'MEDIUMINT UNSIGNED',
1844: restrictions => 'NOT NULL' },
1845: { name => 'parameter',
1846: type => 'TINYTEXT',
1847: restrictions => 'NOT NULL' },
1848: { name => 'value',
1849: type => 'MEDIUMTEXT' },
1850: ],
1851: 'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
1852: };
1853: #
1854: # Create the tables
1855: my $tableid;
1856: $tableid = &Apache::lonmysql::create_table($symb_table_def);
1857: if (! defined($tableid)) {
1858: &Apache::lonnet::logthis("error creating symb_table: ".
1859: &Apache::lonmysql::get_error());
1860: return 1;
1861: }
1862: #
1863: $tableid = &Apache::lonmysql::create_table($part_table_def);
1864: if (! defined($tableid)) {
1865: &Apache::lonnet::logthis("error creating part_table: ".
1866: &Apache::lonmysql::get_error());
1867: return 2;
1868: }
1869: #
1870: $tableid = &Apache::lonmysql::create_table($student_table_def);
1871: if (! defined($tableid)) {
1872: &Apache::lonnet::logthis("error creating student_table: ".
1873: &Apache::lonmysql::get_error());
1874: return 3;
1875: }
1876: #
1877: $tableid = &Apache::lonmysql::create_table($updatetime_table_def);
1878: if (! defined($tableid)) {
1879: &Apache::lonnet::logthis("error creating updatetime_table: ".
1880: &Apache::lonmysql::get_error());
1881: return 4;
1882: }
1883: #
1884: $tableid = &Apache::lonmysql::create_table($performance_table_def);
1885: if (! defined($tableid)) {
1886: &Apache::lonnet::logthis("error creating preformance_table: ".
1887: &Apache::lonmysql::get_error());
1888: return 5;
1889: }
1890: #
1891: $tableid = &Apache::lonmysql::create_table($parameters_table_def);
1892: if (! defined($tableid)) {
1893: &Apache::lonnet::logthis("error creating parameters_table: ".
1894: &Apache::lonmysql::get_error());
1895: return 6;
1896: }
1897: return 0;
1898: }
1899:
1900: ################################################
1901: ################################################
1902:
1903: =pod
1904:
1905: =item &get_part_id()
1906:
1907: Get the MySQL id of a problem part string.
1908:
1909: Input: $part
1910:
1911: Output: undef on error, integer $part_id on success.
1912:
1913: =item &get_part()
1914:
1915: Get the string describing a part from the MySQL id of the problem part.
1916:
1917: Input: $part_id
1918:
1919: Output: undef on error, $part string on success.
1920:
1921: =cut
1922:
1923: ################################################
1924: ################################################
1925:
1926: my %ids_by_part;
1927: my %parts_by_id;
1928:
1929: sub get_part_id {
1930: my ($part) = @_;
1931: if (! exists($ids_by_part{$part})) {
1932: &Apache::lonmysql::store_row($part_table,[undef,$part]);
1933: undef(%ids_by_part);
1934: my @Result = &Apache::lonmysql::get_rows($part_table);
1935: foreach (@Result) {
1936: $ids_by_part{$_->[1]}=$_->[0];
1937: }
1938: }
1939: return $ids_by_part{$part} if (exists($ids_by_part{$part}));
1940: return undef; # error
1941: }
1942:
1943: sub get_part {
1944: my ($part_id) = @_;
1945: if (! exists($parts_by_id{$part_id}) ||
1946: ! defined($parts_by_id{$part_id}) ||
1947: $parts_by_id{$part_id} eq '') {
1948: my @Result = &Apache::lonmysql::get_rows($part_table);
1949: foreach (@Result) {
1950: $parts_by_id{$_->[0]}=$_->[1];
1951: }
1952: }
1953: return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
1954: return undef; # error
1955: }
1956:
1957: ################################################
1958: ################################################
1959:
1960: =pod
1961:
1962: =item &get_symb_id()
1963:
1964: Get the MySQL id of a symb.
1965:
1966: Input: $symb
1967:
1968: Output: undef on error, integer $symb_id on success.
1969:
1970: =item &get_symb()
1971:
1972: Get the symb associated with a MySQL symb_id.
1973:
1974: Input: $symb_id
1975:
1976: Output: undef on error, $symb on success.
1977:
1978: =cut
1979:
1980: ################################################
1981: ################################################
1982:
1983: my %ids_by_symb;
1984: my %symbs_by_id;
1985:
1986: sub get_symb_id {
1987: my ($symb) = @_;
1988: if (! exists($ids_by_symb{$symb})) {
1989: &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
1990: undef(%ids_by_symb);
1991: my @Result = &Apache::lonmysql::get_rows($symb_table);
1992: foreach (@Result) {
1993: $ids_by_symb{$_->[1]}=$_->[0];
1994: }
1995: }
1996: return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
1997: return undef; # error
1998: }
1999:
2000: sub get_symb {
2001: my ($symb_id) = @_;
2002: if (! exists($symbs_by_id{$symb_id}) ||
2003: ! defined($symbs_by_id{$symb_id}) ||
2004: $symbs_by_id{$symb_id} eq '') {
2005: my @Result = &Apache::lonmysql::get_rows($symb_table);
2006: foreach (@Result) {
2007: $symbs_by_id{$_->[0]}=$_->[1];
2008: }
2009: }
2010: return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
2011: return undef; # error
2012: }
2013:
2014: ################################################
2015: ################################################
2016:
2017: =pod
2018:
2019: =item &get_student_id()
2020:
2021: Get the MySQL id of a student.
2022:
2023: Input: $sname, $dom
2024:
2025: Output: undef on error, integer $student_id on success.
2026:
2027: =item &get_student()
2028:
2029: Get student username:domain associated with the MySQL student_id.
2030:
2031: Input: $student_id
2032:
2033: Output: undef on error, string $student (username:domain) on success.
2034:
2035: =cut
2036:
2037: ################################################
2038: ################################################
2039:
2040: my %ids_by_student;
2041: my %students_by_id;
2042:
2043: sub get_student_id {
2044: my ($sname,$sdom) = @_;
2045: my $student = $sname.':'.$sdom;
2046: if (! exists($ids_by_student{$student})) {
2047: &Apache::lonmysql::store_row($student_table,[undef,$student]);
2048: undef(%ids_by_student);
2049: my @Result = &Apache::lonmysql::get_rows($student_table);
2050: foreach (@Result) {
2051: $ids_by_student{$_->[1]}=$_->[0];
2052: }
2053: }
2054: return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
2055: return undef; # error
2056: }
2057:
2058: sub get_student {
2059: my ($student_id) = @_;
2060: if (! exists($students_by_id{$student_id}) ||
2061: ! defined($students_by_id{$student_id}) ||
2062: $students_by_id{$student_id} eq '') {
2063: my @Result = &Apache::lonmysql::get_rows($student_table);
2064: foreach (@Result) {
2065: $students_by_id{$_->[0]}=$_->[1];
2066: }
2067: }
2068: return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
2069: return undef; # error
2070: }
2071:
2072: ################################################
2073: ################################################
2074:
2075: =pod
2076:
2077: =item &update_student_data()
2078:
2079: Input: $sname, $sdom, $courseid
2080:
2081: Output: $returnstatus, \%student_data
2082:
2083: $returnstatus is a string describing any errors that occured. 'okay' is the
2084: default.
2085: \%student_data is the data returned by a call to lonnet::currentdump.
2086:
2087: This subroutine loads a students data using lonnet::currentdump and inserts
2088: it into the MySQL database. The inserts are done on two tables,
2089: $performance_table and $parameters_table. $parameters_table holds the data
2090: that is not included in $performance_table. See the description of
2091: $performance_table elsewhere in this file. The INSERT calls are made
2092: directly by this subroutine, not through lonmysql because we do a 'bulk'
2093: insert which takes advantage of MySQLs non-SQL compliant INSERT command to
2094: insert multiple rows at a time. If anything has gone wrong during this
2095: process, $returnstatus is updated with a description of the error and
2096: \%student_data is returned.
2097:
2098: Notice we do not insert the data and immediately query it. This means it
2099: is possible for there to be data returned this first time that is not
2100: available the second time. CYA.
2101:
2102: =cut
2103:
2104: ################################################
2105: ################################################
2106: sub update_student_data {
2107: my ($sname,$sdom,$courseid) = @_;
2108: #
2109: my $student_id = &get_student_id($sname,$sdom);
2110: my $student = $sname.':'.$sdom;
2111: #
2112: my $returnstatus = 'okay';
2113: #
2114: # Set up database names
2115: &setup_table_names($courseid);
2116: #
2117: # Download students data
2118: my $time_of_retrieval = time;
2119: my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
2120: if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
2121: &Apache::lonnet::logthis('error getting data for '.
2122: $sname.':'.$sdom.' in course '.$courseid.
2123: ':'.$tmp[0]);
2124: $returnstatus = 'error getting data';
2125: return $returnstatus;
2126: }
2127: if (scalar(@tmp) < 1) {
2128: return ('no data',undef);
2129: }
2130: my %student_data = @tmp;
2131: #
2132: # Remove all of the students data from the table
2133: &Apache::lonmysql::remove_from_table($performance_table,'student_id',
2134: $student_id);
2135: #
2136: # Store away the data
2137: #
2138: my $starttime = Time::HiRes::time;
2139: my $elapsed = 0;
2140: my $rows_stored;
2141: my $store_parameters_command = 'INSERT INTO '.$parameters_table.
2142: ' VALUES ';
2143: my $store_performance_command = 'INSERT INTO '.$performance_table.
2144: ' VALUES ';
2145: my $dbh = &Apache::lonmysql::get_dbh();
2146: return 'error' if (! defined($dbh));
2147: while (my ($current_symb,$param_hash) = each(%student_data)) {
2148: #
2149: # make sure the symb is set up properly
2150: my $symb_id = &get_symb_id($current_symb);
2151: #
2152: # Load data into the tables
2153: while (my ($parameter,$value) = each (%$param_hash)) {
2154: my $newstring;
2155: if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
2156: $newstring = "('".join("','",
2157: $symb_id,$student_id,
2158: $parameter,$value)."'),";
2159: if ($newstring !~ /''/) {
2160: $store_parameters_command .= $newstring;
2161: $rows_stored++;
2162: }
2163: }
2164: next if ($parameter !~ /^resource\.(.*)\.solved$/);
2165: #
2166: my $part = $1;
2167: my $part_id = &get_part_id($part);
2168: next if (!defined($part_id));
2169: my $solved = $value;
2170: my $tries = $param_hash->{'resource.'.$part.'.tries'};
2171: my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
2172: my $award = $param_hash->{'resource.'.$part.'.award'};
2173: my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
2174: my $timestamp = $param_hash->{'timestamp'};
2175: $solved = '' if (! defined($awarded));
2176: $tries = '' if (! defined($tries));
2177: $awarded = '' if (! defined($awarded));
2178: $award = '' if (! defined($award));
2179: $awarddetail = '' if (! defined($awarddetail));
2180: $newstring = "('".join("','",$symb_id,$student_id,$part_id,
2181: $solved,$tries,$awarded,$award,
2182: $awarddetail,$timestamp)."'),";
2183: $store_performance_command .= $newstring;
2184: $rows_stored++;
2185: }
2186: }
2187: chop $store_parameters_command;
2188: chop $store_performance_command;
2189: my $start = Time::HiRes::time;
2190: $dbh->do($store_parameters_command);
2191: if ($dbh->err()) {
2192: &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
2193: &Apache::lonnet::logthis('command = '.$store_performance_command);
2194: $returnstatus = 'error: unable to insert parameters into database';
2195: return $returnstatus,\%student_data;
2196: }
2197: $dbh->do($store_performance_command);
2198: if ($dbh->err()) {
2199: &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
2200: &Apache::lonnet::logthis('command = '.$store_parameters_command);
2201: $returnstatus = 'error: unable to insert performance into database';
2202: return $returnstatus,\%student_data;
2203: }
2204: $elapsed += Time::HiRes::time - $start;
2205: #
2206: # Set the students update time
2207: &Apache::lonmysql::replace_row($updatetime_table,
2208: [$student,$time_of_retrieval]);
2209: &Apache::lonnet::logthis('store took: '.(Time::HiRes::time - $starttime).' for '.$rows_stored);
2210: &Apache::lonnet::logthis('mysql store took: '.$elapsed.' for '.$rows_stored);
2211: return ($returnstatus,\%student_data);
2212: }
2213:
2214: ################################################
2215: ################################################
2216:
2217: =pod
2218:
2219: =item &ensure_current_data()
2220:
2221: Input: $sname, $sdom, $courseid
2222:
2223: Output: $status, $data
2224:
2225: This routine ensures the data for a given student is up to date. It calls
2226: &init_dbs() if the tables do not exist. The $updatetime_table is queried
2227: to determine the time of the last update. If the students data is out of
2228: date, &update_student_data() is called. The return values from the call
2229: to &update_student_data() are returned.
2230:
2231: =cut
2232:
2233: ################################################
2234: ################################################
2235: sub ensure_current_data {
2236: my ($sname,$sdom,$courseid) = @_;
2237: my $status = 'okay'; # return value
2238: #
2239: &setup_table_names($courseid);
2240: #
2241: # if the tables do not exist, make them
2242: my @CurrentTable = &Apache::lonmysql::tables_in_db();
2243: my ($found_symb,$found_student,$found_part,$found_update,
2244: $found_performance,$found_parameters);
2245: foreach (@CurrentTable) {
2246: $found_symb = 1 if ($_ eq $symb_table);
2247: $found_student = 1 if ($_ eq $student_table);
2248: $found_part = 1 if ($_ eq $part_table);
2249: $found_update = 1 if ($_ eq $updatetime_table);
2250: $found_performance = 1 if ($_ eq $performance_table);
2251: $found_parameters = 1 if ($_ eq $parameters_table);
2252: }
2253: if (!$found_symb || !$found_update ||
2254: !$found_student || !$found_part ||
2255: !$found_performance || !$found_parameters) {
2256: if (&init_dbs($courseid)) {
2257: return 'error';
2258: }
2259: }
2260: #
2261: # Get the update time for the user
2262: my $updatetime = 0;
2263: my $modifiedtime = 1;
2264: #
2265: my $student = $sname.':'.$sdom;
2266: my @Result = &Apache::lonmysql::get_rows($updatetime_table,
2267: "student ='$student'");
2268: my $data = undef;
2269: if (@Result) {
2270: $updatetime = $Result[0]->[1];
2271: }
2272: if ($modifiedtime > $updatetime) {
2273: ($status,$data) = &update_student_data($sname,$sdom,$courseid);
2274: }
2275: return ($status,$data);
2276: }
2277:
2278: ################################################
2279: ################################################
2280:
2281: =pod
2282:
2283: =item &get_student_data_from_performance_cache()
2284:
2285: Input: $sname, $sdom, $symb, $courseid
2286:
2287: Output: hash reference containing the data for the given student.
2288: If $symb is undef, all the students data is returned.
2289:
2290: This routine is the heart of the local caching system. See the description
2291: of $performance_table, $symb_table, $student_table, and $part_table. The
2292: main task is building the MySQL request. The tables appear in the request
2293: in the order in which they should be parsed by MySQL. When searching
2294: on a student the $student_table is used to locate the 'student_id'. All
2295: rows in $performance_table which have a matching 'student_id' are returned,
2296: with data from $part_table and $symb_table which match the entries in
2297: $performance_table, 'part_id' and 'symb_id'. When searching on a symb,
2298: the $symb_table is processed first, with matching rows grabbed from
2299: $performance_table and filled in from $part_table and $student_table in
2300: that order.
2301:
2302: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite
2303: interesting, especially if you play with the order the tables are listed.
2304:
2305: =cut
2306:
2307: ################################################
2308: ################################################
2309: sub get_student_data_from_performance_cache {
2310: my ($sname,$sdom,$symb,$courseid)=@_;
2311: my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
2312: &setup_table_names();
2313: #
2314: # Return hash
2315: my $studentdata;
2316: #
2317: my $dbh = &Apache::lonmysql::get_dbh();
2318: my $request = "SELECT ".
2319: "d.symb,c.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
2320: "a.timestamp ";
2321: if (defined($student)) {
2322: $request .= "FROM $student_table AS b ".
2323: "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
2324: "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
2325: "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
2326: "WHERE student='$student'";
2327: if (defined($symb) && $symb ne '') {
2328: $request .= " AND d.symb='".$dbh->quote($symb)."'";
2329: }
2330: } elsif (defined($symb) && $symb ne '') {
2331: $request .= "FROM $symb_table as d ".
2332: "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
2333: "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
2334: "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
2335: "WHERE symb='".$dbh->quote($symb)."'";
2336: }
2337: my $starttime = Time::HiRes::time;
2338: my $rows_retrieved = 0;
2339: my $sth = $dbh->prepare($request);
2340: $sth->execute();
2341: if ($sth->err()) {
2342: &Apache::lonnet::logthis("Unable to execute MySQL request:");
2343: &Apache::lonnet::logthis("\n".$request."\n");
2344: &Apache::lonnet::logthis("error is:".$sth->errstr());
2345: return undef;
2346: }
2347: foreach my $row (@{$sth->fetchall_arrayref}) {
2348: $rows_retrieved++;
2349: my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) =
2350: (@$row);
2351: my $base = 'resource.'.$part;
2352: $studentdata->{$symb}->{$base.'.solved'} = $solved;
2353: $studentdata->{$symb}->{$base.'.tries'} = $tries;
2354: $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
2355: $studentdata->{$symb}->{$base.'.award'} = $award;
2356: $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
2357: $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
2358: }
2359: &Apache::lonnet::logthis('retrieve took: '.(Time::HiRes::time - $starttime).' for '.$rows_retrieved);
2360: return $studentdata;
2361: }
2362:
2363: ################################################
2364: ################################################
2365:
2366: =pod
2367:
2368: =item &get_current_state()
2369:
2370: Input: $sname,$sdom,$symb,$courseid
2371:
2372: Output: Described below
2373:
2374: Retrieve the current status of a students performance. $sname and
2375: $sdom are the only required parameters. If $symb is undef the results
2376: of an &Apache::lonnet::currentdump() will be returned.
2377: If $courseid is undef it will be retrieved from the environment.
2378:
2379: The return structure is based on &Apache::lonnet::currentdump. If
2380: $symb is unspecified, all the students data is returned in a hash of
2381: the form:
2382: (
2383: symb1 => { param1 => value1, param2 => value2 ... },
2384: symb2 => { param1 => value1, param2 => value2 ... },
2385: )
2386:
2387: If $symb is specified, a hash of
2388: (
2389: param1 => value1,
2390: param2 => value2,
2391: )
2392: is returned.
2393:
2394: If no data is found for $symb, or if the student has no performance data,
2395: an empty list is returned.
2396:
2397: =cut
2398:
2399: ################################################
2400: ################################################
2401: sub get_current_state {
2402: my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
2403: if ($current_course ne $courseid) {
2404: # Clear out variables
2405: undef(%ids_by_part);
2406: undef(%parts_by_id);
2407: undef(%ids_by_symb);
2408: undef(%symbs_by_id);
2409: undef(%ids_by_student);
2410: undef(%students_by_id);
2411: $current_course = $courseid;
2412: }
2413: return () if (! defined($sname) || ! defined($sdom));
2414: #
2415: $courseid = $ENV{'request.course.id'} if (! defined($courseid));
2416: #
2417: my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
2418: #
2419: if (defined($data)) {
2420: return %$data;
2421: } elsif ($status eq 'no data') {
2422: return ();
2423: } else {
2424: if ($status ne 'okay' && $status ne '') {
2425: &Apache::lonnet::logthis('status = '.$status);
2426: return ();
2427: }
2428: my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
2429: $symb,$courseid);
2430: return %$returnhash if (defined($returnhash));
2431: }
2432: return ();
2433: }
2434:
2435: ################################################
2436: ################################################
2437:
2438: =pod
2439:
2440: =back
2441:
2442: =item End of Local Data Caching Subroutines
2443:
2444: =cut
2445:
2446: ################################################
2447: ################################################
2448:
2449:
2450: }
2451: ################################################
2452: ################################################
2453:
2454: =pod
2455:
2456: =head3 Classlist Subroutines
2457:
2458: =item &get_classlist();
2459:
2460: Retrieve the classist of a given class or of the current class. Student
2461: information is returned from the classlist.db file and, if needed,
2462: from the students environment.
2463:
2464: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
2465: and course number, respectively). Any omitted arguments will be taken
2466: from the current environment ($ENV{'request.course.id'},
2467: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
2468:
2469: Returns a reference to a hash which contains:
2470: keys '$sname:$sdom'
2471: values [$sdom,$sname,$end,$start,$id,$section,$fullname,$status]
2472:
2473: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
2474: as indices into the returned list to future-proof clients against
2475: changes in the list order.
2476:
2477: =cut
2478:
2479: ################################################
2480: ################################################
2481:
2482: sub CL_SDOM { return 0; }
2483: sub CL_SNAME { return 1; }
2484: sub CL_END { return 2; }
2485: sub CL_START { return 3; }
2486: sub CL_ID { return 4; }
2487: sub CL_SECTION { return 5; }
2488: sub CL_FULLNAME { return 6; }
2489: sub CL_STATUS { return 7; }
2490:
2491: sub get_classlist {
2492: my ($cid,$cdom,$cnum) = @_;
2493: $cid = $cid || $ENV{'request.course.id'};
2494: $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
2495: $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
2496: my $now = time;
2497: #
2498: my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
2499: while (my ($student,$info) = each(%classlist)) {
2500: return undef if ($student =~ /^(con_lost|error|no_such_host)/i);
2501: my ($sname,$sdom) = split(/:/,$student);
2502: my @Values = split(/:/,$info);
2503: my ($end,$start,$id,$section,$fullname);
2504: if (@Values > 2) {
2505: ($end,$start,$id,$section,$fullname) = @Values;
2506: } else { # We have to get the data ourselves
2507: ($end,$start) = @Values;
2508: $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
2509: my %info=&Apache::lonnet::get('environment',
2510: ['firstname','middlename',
2511: 'lastname','generation','id'],
2512: $sdom, $sname);
2513: my ($tmp) = keys(%info);
2514: if ($tmp =~/^(con_lost|error|no_such_host)/i) {
2515: $fullname = 'not available';
2516: $id = 'not available';
2517: &Apache::lonnet::logthis('unable to retrieve environment '.
2518: 'for '.$sname.':'.$sdom);
2519: } else {
2520: $fullname = &ProcessFullName(@info{qw/lastname generation
2521: firstname middlename/});
2522: $id = $info{'id'};
2523: }
2524: # Update the classlist with this students information
2525: if ($fullname ne 'not available') {
2526: my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
2527: my $reply=&Apache::lonnet::cput('classlist',
2528: {$student => $enrolldata},
2529: $cdom,$cnum);
2530: if ($reply !~ /^(ok|delayed)/) {
2531: &Apache::lonnet::logthis('Unable to update classlist for '.
2532: 'student '.$sname.':'.$sdom.
2533: ' error:'.$reply);
2534: }
2535: }
2536: }
2537: my $status='Expired';
2538: if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
2539: $status='Active';
2540: }
2541: $classlist{$student} =
2542: [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
2543: }
2544: if (wantarray()) {
2545: return (\%classlist,['domain','username','end','start','id',
2546: 'section','fullname','status']);
2547: } else {
2548: return \%classlist;
2549: }
2550: }
2551:
2552: # ----- END HELPER FUNCTIONS --------------------------------------------
2553:
2554: 1;
2555: __END__
2556:
2557:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>