Annotation of loncom/interface/lonspreadsheet.pm, revision 1.151
1.79 matthew 1: #
1.151 ! matthew 2: # $Id: lonspreadsheet.pm,v 1.150 2002/11/26 14:58:41 matthew Exp $
1.79 matthew 3: #
4: # Copyright Michigan State University Board of Trustees
5: #
6: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
7: #
8: # LON-CAPA is free software; you can redistribute it and/or modify
9: # it under the terms of the GNU General Public License as published by
10: # the Free Software Foundation; either version 2 of the License, or
11: # (at your option) any later version.
12: #
13: # LON-CAPA is distributed in the hope that it will be useful,
14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16: # GNU General Public License for more details.
17: #
18: # You should have received a copy of the GNU General Public License
19: # along with LON-CAPA; if not, write to the Free Software
20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21: #
22: # /home/httpd/html/adm/gpl.txt
23: #
24: # http://www.lon-capa.org/
25: #
1.1 www 26: # The LearningOnline Network with CAPA
27: # Spreadsheet/Grades Display Handler
28: #
1.80 matthew 29: # POD required stuff:
30:
31: =head1 NAME
32:
33: lonspreadsheet
34:
35: =head1 SYNOPSIS
36:
37: Spreadsheet interface to internal LON-CAPA data
38:
39: =head1 DESCRIPTION
40:
41: Lonspreadsheet provides course coordinators the ability to manage their
42: students grades online. The students are able to view their own grades, but
43: not the grades of their peers. The spreadsheet is highly customizable,
44: offering the ability to use Perl code to manipulate data, as well as many
45: built-in functions.
46:
47: =head2 Functions available to user of lonspreadsheet
48:
49: =over 4
50:
51: =cut
1.1 www 52:
53: package Apache::lonspreadsheet;
1.36 www 54:
1.1 www 55: use strict;
1.140 matthew 56: use Apache::Constants qw(:common :http);
57: use Apache::lonnet;
58: use Apache::lonhtmlcommon;
59: use Apache::loncoursedata;
60: use Apache::File();
1.1 www 61: use Safe;
1.3 www 62: use Safe::Hole;
1.1 www 63: use Opcode;
1.19 www 64: use GDBM_File;
1.3 www 65: use HTML::TokeParser;
1.134 matthew 66: use Spreadsheet::WriteExcel;
1.136 matthew 67:
1.11 www 68: #
1.113 matthew 69: # Caches for coursewide information
70: #
71: my %Section;
72:
73: #
1.44 www 74: # Caches for previously calculated spreadsheets
75: #
76:
77: my %oldsheets;
1.46 www 78: my %loadedcaches;
1.47 www 79: my %expiredates;
1.44 www 80:
81: #
1.39 www 82: # Cache for stores of an individual user
83: #
84:
85: my $cachedassess;
86: my %cachedstores;
87:
88: #
1.11 www 89: # These cache hashes need to be independent of user, resource and course
1.27 www 90: # (user and course can/should be in the keys)
1.11 www 91: #
1.33 www 92:
93: my %spreadsheets;
94: my %courserdatas;
95: my %userrdatas;
96: my %defaultsheets;
1.136 matthew 97: my %rowlabel_cache;
1.27 www 98:
1.11 www 99: #
100: # These global hashes are dependent on user, course and resource,
101: # and need to be initialized every time when a sheet is calculated
102: #
103: my %courseopt;
104: my %useropt;
105: my %parmhash;
106:
1.95 www 107: #
108: # Some hashes for stats on timing and performance
109: #
110:
111: my %starttimes;
112: my %usedtimes;
1.96 www 113: my %numbertimes;
1.95 www 114:
1.28 www 115: # Stuff that only the screen handler can know
116:
117: my $includedir;
118: my $tmpdir;
119:
1.5 www 120: # =============================================================================
121: # ===================================== Implements an instance of a spreadsheet
1.4 www 122:
1.118 matthew 123: ##
124: ## mask - used to reside in the safe space.
125: ##
1.1 www 126: sub mask {
127: my ($lower,$upper)=@_;
1.132 matthew 128: $upper = $lower if (! defined($upper));
1.125 matthew 129: #
130: my ($la,$ld) = ($lower=~/([A-Za-z]|\*)(\d+|\*)/);
131: my ($ua,$ud) = ($upper=~/([A-Za-z]|\*)(\d+|\*)/);
132: #
1.1 www 133: my $alpha='';
134: my $num='';
1.125 matthew 135: #
1.1 www 136: if (($la eq '*') || ($ua eq '*')) {
1.132 matthew 137: $alpha='[A-Za-z]';
1.1 www 138: } else {
1.7 www 139: if (($la=~/[A-Z]/) && ($ua=~/[A-Z]/) ||
140: ($la=~/[a-z]/) && ($ua=~/[a-z]/)) {
141: $alpha='['.$la.'-'.$ua.']';
142: } else {
143: $alpha='['.$la.'-Za-'.$ua.']';
144: }
1.1 www 145: }
146: if (($ld eq '*') || ($ud eq '*')) {
147: $num='\d+';
148: } else {
149: if (length($ld)!=length($ud)) {
150: $num.='(';
1.78 matthew 151: foreach ($ld=~m/\d/g) {
1.1 www 152: $num.='['.$_.'-9]';
1.78 matthew 153: }
1.1 www 154: if (length($ud)-length($ld)>1) {
155: $num.='|\d{'.(length($ld)+1).','.(length($ud)-1).'}';
156: }
157: $num.='|';
1.78 matthew 158: foreach ($ud=~m/\d/g) {
1.1 www 159: $num.='[0-'.$_.']';
1.78 matthew 160: }
1.1 www 161: $num.=')';
162: } else {
163: my @lda=($ld=~m/\d/g);
164: my @uda=($ud=~m/\d/g);
1.118 matthew 165: my $i;
166: my $j=0;
167: my $notdone=1;
1.7 www 168: for ($i=0;($i<=$#lda)&&($notdone);$i++) {
1.1 www 169: if ($lda[$i]==$uda[$i]) {
170: $num.=$lda[$i];
171: $j=$i;
1.7 www 172: } else {
173: $notdone=0;
1.1 www 174: }
175: }
176: if ($j<$#lda-1) {
177: $num.='('.$lda[$j+1];
178: for ($i=$j+2;$i<=$#lda;$i++) {
179: $num.='['.$lda[$i].'-9]';
180: }
181: if ($uda[$j+1]-$lda[$j+1]>1) {
182: $num.='|['.($lda[$j+1]+1).'-'.($uda[$j+1]-1).']\d{'.
183: ($#lda-$j-1).'}';
184: }
185: $num.='|'.$uda[$j+1];
186: for ($i=$j+2;$i<=$#uda;$i++) {
187: $num.='[0-'.$uda[$i].']';
188: }
189: $num.=')';
190: } else {
1.125 matthew 191: if ($lda[-1]!=$uda[-1]) {
192: $num.='['.$lda[-1].'-'.$uda[-1].']';
1.7 www 193: }
1.1 www 194: }
195: }
196: }
1.4 www 197: return '^'.$alpha.$num."\$";
1.80 matthew 198: }
199:
1.118 matthew 200: sub initsheet {
201: my $safeeval = new Safe(shift);
202: my $safehole = new Safe::Hole;
203: $safeeval->permit("entereval");
204: $safeeval->permit(":base_math");
205: $safeeval->permit("sort");
206: $safeeval->deny(":base_io");
207: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
208: $safehole->wrap(\&Apache::lonspreadsheet::mask,$safeeval,'&mask');
209: $safeeval->share('$@');
210: my $code=<<'ENDDEFS';
211: # ---------------------------------------------------- Inside of the safe space
212:
213: #
214: # f: formulas
215: # t: intermediate format (variable references expanded)
216: # v: output values
217: # c: preloaded constants (A-column)
218: # rl: row label
219: # os: other spreadsheets (for student spreadsheet only)
220:
1.119 matthew 221: undef %sheet_values; # Holds the (computed, final) values for the sheet
222: # This is only written to by &calc, the spreadsheet computation routine.
223: # It is read by many functions
224: undef %t; # Holds the values of the spreadsheet temporarily. Set in &sett,
225: # which does the translation of strings like C5 into the value in C5.
226: # Used in &calc - %t holds the values that are actually eval'd.
227: undef %f; # Holds the formulas for each cell. This is the users
228: # (spreadsheet authors) data for each cell.
229: # set by &setformulas and returned by &getformulas
230: # &setformulas is called by &readsheet, &tmpread, &updateclasssheet,
231: # &updatestudentassesssheet, &loadstudent, &loadcourse
232: # &getformulas is called by &writesheet, &tmpwrite, &updateclasssheet,
233: # &updatestudentassesssheet, &loadstudent, &loadcourse, &loadassessment,
234: undef %c; # Holds the constants for a sheet. In the assessment
235: # sheets, this is the A column. Used in &MINPARM, &MAXPARM, &expandnamed,
236: # &sett, and &setconstants. There is no &getconstants.
237: # &setconstants is called by &loadstudent, &loadcourse, &load assessment,
238: undef @os; # Holds the names of other spreadsheets - this is used to specify
239: # the spreadsheets that are available for the assessment sheet.
240: # Set by &setothersheets. &setothersheets is called by &handler. A
241: # related subroutine is &othersheets.
1.132 matthew 242: #$errorlog = '';
1.118 matthew 243:
244: $maxrow = 0;
245: $sheettype = '';
246:
247: # filename/reference of the sheet
248: $filename = '';
249:
250: # user data
251: $uname = '';
252: $uhome = '';
253: $udom = '';
254:
255: # course data
256:
257: $csec = '';
258: $chome= '';
259: $cnum = '';
260: $cdom = '';
261: $cid = '';
262: $coursefilename = '';
263:
264: # symb
265:
266: $usymb = '';
267:
268: # error messages
269: $errormsg = '';
270:
271:
1.80 matthew 272: #-------------------------------------------------------
273:
274: =item UWCALC(hashname,modules,units,date)
275:
276: returns the proportion of the module
277: weights not previously completed by the student.
278:
279: =over 4
280:
281: =item hashname
282:
283: name of the hash the module dates have been inserted into
284:
285: =item modules
286:
287: reference to a cell which contains a comma deliminated list of modules
288: covered by the assignment.
289:
290: =item units
291:
292: reference to a cell which contains a comma deliminated list of module
293: weights with respect to the assignment
294:
295: =item date
296:
297: reference to a cell which contains the date the assignment was completed.
298:
299: =back
300:
301: =cut
302:
303: #-------------------------------------------------------
304: sub UWCALC {
305: my ($hashname,$modules,$units,$date) = @_;
306: my @Modules = split(/,/,$modules);
307: my @Units = split(/,/,$units);
308: my $total_weight;
309: foreach (@Units) {
310: $total_weight += $_;
311: }
312: my $usum=0;
313: for (my $i=0; $i<=$#Modules; $i++) {
314: if (&HASH($hashname,$Modules[$i]) eq $date) {
315: $usum += $Units[$i];
316: }
317: }
318: return $usum/$total_weight;
319: }
320:
321: #-------------------------------------------------------
322:
323: =item CDLSUM(list)
324:
325: returns the sum of the elements in a cell which contains
326: a Comma Deliminate List of numerical values.
327: 'list' is a reference to a cell which contains a comma deliminated list.
328:
329: =cut
330:
331: #-------------------------------------------------------
332: sub CDLSUM {
333: my ($list)=@_;
334: my $sum;
335: foreach (split/,/,$list) {
336: $sum += $_;
337: }
338: return $sum;
339: }
340:
341: #-------------------------------------------------------
342:
343: =item CDLITEM(list,index)
344:
345: returns the item at 'index' in a Comma Deliminated List.
346:
347: =over 4
348:
349: =item list
350:
351: reference to a cell which contains a comma deliminated list.
352:
353: =item index
354:
355: the Perl index of the item requested (first element in list has
356: an index of 0)
357:
358: =back
359:
360: =cut
361:
362: #-------------------------------------------------------
363: sub CDLITEM {
364: my ($list,$index)=@_;
365: my @Temp = split/,/,$list;
366: return $Temp[$index];
367: }
368:
369: #-------------------------------------------------------
370:
371: =item CDLHASH(name,key,value)
372:
373: loads a comma deliminated list of keys into
374: the hash 'name', all with a value of 'value'.
375:
376: =over 4
377:
378: =item name
379:
380: name of the hash.
381:
382: =item key
383:
384: (a pointer to) a comma deliminated list of keys.
385:
386: =item value
387:
388: a single value to be entered for each key.
389:
390: =back
391:
392: =cut
393:
394: #-------------------------------------------------------
395: sub CDLHASH {
396: my ($name,$key,$value)=@_;
397: my @Keys;
398: my @Values;
399: # Check to see if we have multiple $key values
400: if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
401: my $keymask = &mask($key);
402: # Assume the keys are addresses
1.104 matthew 403: my @Temp = grep /$keymask/,keys(%sheet_values);
404: @Keys = $sheet_values{@Temp};
1.80 matthew 405: } else {
406: $Keys[0]= $key;
407: }
408: my @Temp;
409: foreach $key (@Keys) {
410: @Temp = (@Temp, split/,/,$key);
411: }
412: @Keys = @Temp;
413: if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
414: my $valmask = &mask($value);
1.104 matthew 415: my @Temp = grep /$valmask/,keys(%sheet_values);
416: @Values =$sheet_values{@Temp};
1.80 matthew 417: } else {
418: $Values[0]= $value;
419: }
420: $value = $Values[0];
421: # Add values to hash
422: for (my $i = 0; $i<=$#Keys; $i++) {
423: my $key = $Keys[$i];
424: if (! exists ($hashes{$name}->{$key})) {
425: $hashes{$name}->{$key}->[0]=$value;
426: } else {
427: my @Temp = sort(@{$hashes{$name}->{$key}},$value);
428: $hashes{$name}->{$key} = \@Temp;
429: }
430: }
431: return "hash '$name' updated";
432: }
433:
434: #-------------------------------------------------------
435:
436: =item GETHASH(name,key,index)
437:
438: returns the element in hash 'name'
439: reference by the key 'key', at index 'index' in the values list.
440:
441: =cut
442:
443: #-------------------------------------------------------
444: sub GETHASH {
445: my ($name,$key,$index)=@_;
446: if (! defined($index)) {
447: $index = 0;
448: }
449: if ($key =~ /^[A-z]\d+$/) {
1.104 matthew 450: $key = $sheet_values{$key};
1.80 matthew 451: }
452: return $hashes{$name}->{$key}->[$index];
453: }
454:
455: #-------------------------------------------------------
456:
457: =item CLEARHASH(name)
458:
459: clears all the values from the hash 'name'
460:
461: =item CLEARHASH(name,key)
462:
463: clears all the values from the hash 'name' associated with the given key.
464:
465: =cut
466:
467: #-------------------------------------------------------
468: sub CLEARHASH {
469: my ($name,$key)=@_;
470: if (defined($key)) {
471: if (exists($hashes{$name}->{$key})) {
472: $hashes{$name}->{$key}=undef;
473: return "hash '$name' key '$key' cleared";
474: }
475: } else {
476: if (exists($hashes{$name})) {
477: $hashes{$name}=undef;
478: return "hash '$name' cleared";
479: }
480: }
481: return "Error in clearing hash";
482: }
483:
484: #-------------------------------------------------------
485:
486: =item HASH(name,key,value)
487:
488: loads values into an internal hash. If a key
489: already has a value associated with it, the values are sorted numerically.
490:
491: =item HASH(name,key)
492:
493: returns the 0th value in the hash 'name' associated with 'key'.
494:
495: =cut
496:
497: #-------------------------------------------------------
498: sub HASH {
499: my ($name,$key,$value)=@_;
500: my @Keys;
501: undef @Keys;
502: my @Values;
503: # Check to see if we have multiple $key values
504: if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
505: my $keymask = &mask($key);
506: # Assume the keys are addresses
1.104 matthew 507: my @Temp = grep /$keymask/,keys(%sheet_values);
508: @Keys = $sheet_values{@Temp};
1.80 matthew 509: } else {
510: $Keys[0]= $key;
511: }
512: # If $value is empty, return the first value associated
513: # with the first key.
514: if (! $value) {
515: return $hashes{$name}->{$Keys[0]}->[0];
516: }
517: # Check to see if we have multiple $value(s)
518: if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
519: my $valmask = &mask($value);
1.104 matthew 520: my @Temp = grep /$valmask/,keys(%sheet_values);
521: @Values =$sheet_values{@Temp};
1.80 matthew 522: } else {
523: $Values[0]= $value;
524: }
525: # Add values to hash
526: for (my $i = 0; $i<=$#Keys; $i++) {
527: my $key = $Keys[$i];
528: my $value = ($i<=$#Values ? $Values[$i] : $Values[0]);
529: if (! exists ($hashes{$name}->{$key})) {
530: $hashes{$name}->{$key}->[0]=$value;
531: } else {
532: my @Temp = sort(@{$hashes{$name}->{$key}},$value);
533: $hashes{$name}->{$key} = \@Temp;
534: }
535: }
536: return $Values[-1];
1.1 www 537: }
538:
1.84 matthew 539: #-------------------------------------------------------
540:
541: =item NUM(range)
542:
543: returns the number of items in the range.
544:
545: =cut
546:
547: #-------------------------------------------------------
1.1 www 548: sub NUM {
549: my $mask=mask(@_);
1.104 matthew 550: my $num= $#{@{grep(/$mask/,keys(%sheet_values))}}+1;
1.1 www 551: return $num;
552: }
553:
554: sub BIN {
555: my ($low,$high,$lower,$upper)=@_;
556: my $mask=mask($lower,$upper);
557: my $num=0;
1.104 matthew 558: foreach (grep /$mask/,keys(%sheet_values)) {
559: if (($sheet_values{$_}>=$low) && ($sheet_values{$_}<=$high)) {
1.1 www 560: $num++;
561: }
1.78 matthew 562: }
1.1 www 563: return $num;
564: }
565:
566:
1.84 matthew 567: #-------------------------------------------------------
568:
569: =item SUM(range)
570:
571: returns the sum of items in the range.
572:
573: =cut
574:
575: #-------------------------------------------------------
1.1 www 576: sub SUM {
577: my $mask=mask(@_);
578: my $sum=0;
1.104 matthew 579: foreach (grep /$mask/,keys(%sheet_values)) {
580: $sum+=$sheet_values{$_};
1.78 matthew 581: }
1.1 www 582: return $sum;
583: }
584:
1.84 matthew 585: #-------------------------------------------------------
586:
587: =item MEAN(range)
588:
589: compute the average of the items in the range.
590:
591: =cut
592:
593: #-------------------------------------------------------
1.1 www 594: sub MEAN {
595: my $mask=mask(@_);
1.132 matthew 596: my $sum=0;
597: my $num=0;
1.104 matthew 598: foreach (grep /$mask/,keys(%sheet_values)) {
599: $sum+=$sheet_values{$_};
1.1 www 600: $num++;
1.78 matthew 601: }
1.1 www 602: if ($num) {
603: return $sum/$num;
604: } else {
605: return undef;
606: }
607: }
608:
1.84 matthew 609: #-------------------------------------------------------
610:
611: =item STDDEV(range)
612:
613: compute the standard deviation of the items in the range.
614:
615: =cut
616:
617: #-------------------------------------------------------
1.1 www 618: sub STDDEV {
619: my $mask=mask(@_);
620: my $sum=0; my $num=0;
1.104 matthew 621: foreach (grep /$mask/,keys(%sheet_values)) {
622: $sum+=$sheet_values{$_};
1.1 www 623: $num++;
1.78 matthew 624: }
1.1 www 625: unless ($num>1) { return undef; }
626: my $mean=$sum/$num;
627: $sum=0;
1.104 matthew 628: foreach (grep /$mask/,keys(%sheet_values)) {
629: $sum+=($sheet_values{$_}-$mean)**2;
1.78 matthew 630: }
1.1 www 631: return sqrt($sum/($num-1));
632: }
633:
1.84 matthew 634: #-------------------------------------------------------
635:
636: =item PROD(range)
637:
638: compute the product of the items in the range.
639:
640: =cut
641:
642: #-------------------------------------------------------
1.1 www 643: sub PROD {
644: my $mask=mask(@_);
645: my $prod=1;
1.104 matthew 646: foreach (grep /$mask/,keys(%sheet_values)) {
647: $prod*=$sheet_values{$_};
1.78 matthew 648: }
1.1 www 649: return $prod;
650: }
651:
1.84 matthew 652: #-------------------------------------------------------
653:
654: =item MAX(range)
655:
656: compute the maximum of the items in the range.
657:
658: =cut
659:
660: #-------------------------------------------------------
1.1 www 661: sub MAX {
662: my $mask=mask(@_);
663: my $max='-';
1.104 matthew 664: foreach (grep /$mask/,keys(%sheet_values)) {
665: unless ($max) { $max=$sheet_values{$_}; }
666: if (($sheet_values{$_}>$max) || ($max eq '-')) { $max=$sheet_values{$_}; }
1.78 matthew 667: }
1.1 www 668: return $max;
669: }
670:
1.84 matthew 671: #-------------------------------------------------------
672:
673: =item MIN(range)
674:
675: compute the minimum of the items in the range.
676:
677: =cut
678:
679: #-------------------------------------------------------
1.1 www 680: sub MIN {
681: my $mask=mask(@_);
682: my $min='-';
1.104 matthew 683: foreach (grep /$mask/,keys(%sheet_values)) {
684: unless ($max) { $max=$sheet_values{$_}; }
685: if (($sheet_values{$_}<$min) || ($min eq '-')) {
686: $min=$sheet_values{$_};
687: }
1.78 matthew 688: }
1.1 www 689: return $min;
690: }
691:
1.84 matthew 692: #-------------------------------------------------------
693:
694: =item SUMMAX(num,lower,upper)
695:
696: compute the sum of the largest 'num' items in the range from
697: 'lower' to 'upper'
698:
699: =cut
700:
701: #-------------------------------------------------------
1.1 www 702: sub SUMMAX {
703: my ($num,$lower,$upper)=@_;
704: my $mask=mask($lower,$upper);
705: my @inside=();
1.104 matthew 706: foreach (grep /$mask/,keys(%sheet_values)) {
707: push (@inside,$sheet_values{$_});
1.78 matthew 708: }
1.1 www 709: @inside=sort(@inside);
710: my $sum=0; my $i;
711: for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) {
712: $sum+=$inside[$i];
713: }
714: return $sum;
715: }
716:
1.84 matthew 717: #-------------------------------------------------------
718:
719: =item SUMMIN(num,lower,upper)
720:
721: compute the sum of the smallest 'num' items in the range from
722: 'lower' to 'upper'
723:
724: =cut
725:
726: #-------------------------------------------------------
1.1 www 727: sub SUMMIN {
728: my ($num,$lower,$upper)=@_;
729: my $mask=mask($lower,$upper);
730: my @inside=();
1.104 matthew 731: foreach (grep /$mask/,keys(%sheet_values)) {
732: $inside[$#inside+1]=$sheet_values{$_};
1.78 matthew 733: }
1.1 www 734: @inside=sort(@inside);
735: my $sum=0; my $i;
736: for ($i=0;(($i<$num) && ($i<=$#inside));$i++) {
737: $sum+=$inside[$i];
738: }
739: return $sum;
740: }
741:
1.103 matthew 742: #-------------------------------------------------------
743:
744: =item MINPARM(parametername)
745:
746: Returns the minimum value of the parameters matching the parametername.
747: parametername should be a string such as 'duedate'.
748:
749: =cut
750:
751: #-------------------------------------------------------
752: sub MINPARM {
753: my ($expression) = @_;
754: my $min = undef;
1.124 matthew 755: study($expression);
1.103 matthew 756: foreach $parameter (keys(%c)) {
757: next if ($parameter !~ /$expression/);
758: if ((! defined($min)) || ($min > $c{$parameter})) {
759: $min = $c{$parameter}
760: }
761: }
762: return $min;
763: }
764:
765: #-------------------------------------------------------
766:
767: =item MAXPARM(parametername)
768:
769: Returns the maximum value of the parameters matching the input parameter name.
770: parametername should be a string such as 'duedate'.
771:
772: =cut
773:
774: #-------------------------------------------------------
775: sub MAXPARM {
776: my ($expression) = @_;
777: my $max = undef;
1.124 matthew 778: study($expression);
1.103 matthew 779: foreach $parameter (keys(%c)) {
780: next if ($parameter !~ /$expression/);
781: if ((! defined($min)) || ($max < $c{$parameter})) {
782: $max = $c{$parameter}
783: }
784: }
785: return $max;
786: }
787:
788: #--------------------------------------------------------
1.59 www 789: sub expandnamed {
790: my $expression=shift;
791: if ($expression=~/^\&/) {
792: my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
793: my @vars=split(/\W+/,$formula);
794: my %values=();
795: undef %values;
1.78 matthew 796: foreach ( @vars ) {
1.59 www 797: my $varname=$_;
798: if ($varname=~/\D/) {
799: $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
800: $varname=~s/$var/\(\\w\+\)/g;
1.78 matthew 801: foreach (keys(%c)) {
1.59 www 802: if ($_=~/$varname/) {
803: $values{$1}=1;
804: }
1.78 matthew 805: }
1.59 www 806: }
1.78 matthew 807: }
1.59 www 808: if ($func eq 'EXPANDSUM') {
809: my $result='';
1.78 matthew 810: foreach (keys(%values)) {
1.59 www 811: my $thissum=$formula;
812: $thissum=~s/$var/$_/g;
813: $result.=$thissum.'+';
1.78 matthew 814: }
1.59 www 815: $result=~s/\+$//;
816: return $result;
817: } else {
818: return 0;
819: }
820: } else {
1.88 matthew 821: # it is not a function, so it is a parameter name
822: # We should do the following:
823: # 1. Take the list of parameter names
824: # 2. look through the list for ones that match the parameter we want
825: # 3. If there are no collisions, return the one that matches
826: # 4. If there is a collision, return 'bad parameter name error'
827: my $returnvalue = '';
828: my @matches = ();
829: $#matches = -1;
1.124 matthew 830: study $expression;
1.88 matthew 831: foreach $parameter (keys(%c)) {
832: push @matches,$parameter if ($parameter =~ /$expression/);
833: }
1.129 matthew 834: if (scalar(@matches) == 0) {
835: $returnvalue = 'unmatched parameter: '.$parameter;
1.128 matthew 836: } elsif (scalar(@matches) == 1) {
1.88 matthew 837: $returnvalue = '$c{\''.$matches[0].'\'}';
1.128 matthew 838: } elsif (scalar(@matches) > 0) {
1.100 matthew 839: # more than one match. Look for a concise one
840: $returnvalue = "'non-unique parameter name : $expression'";
841: foreach (@matches) {
842: if (/^$expression$/) {
843: $returnvalue = '$c{\''.$_.'\'}';
844: }
845: }
1.129 matthew 846: } else {
847: # There was a negative number of matches, which indicates
848: # something is wrong with reality. Better warn the user.
849: $returnvalue = 'bizzare parameter: '.$parameter;
1.88 matthew 850: }
851: return $returnvalue;
1.59 www 852: }
853: }
854:
1.1 www 855: sub sett {
856: %t=();
1.16 www 857: my $pattern='';
858: if ($sheettype eq 'assesscalc') {
859: $pattern='A';
860: } else {
861: $pattern='[A-Z]';
862: }
1.104 matthew 863: # Deal with the template row
1.78 matthew 864: foreach (keys(%f)) {
1.104 matthew 865: next if ($_!~/template\_(\w)/);
866: my $col=$1;
867: next if ($col=~/^$pattern/);
868: foreach (keys(%f)) {
869: next if ($_!~/A(\d+)/);
870: my $trow=$1;
871: next if (! $trow);
872: # Get the name of this cell
873: my $lb=$col.$trow;
874: # Grab the template declaration
875: $t{$lb}=$f{'template_'.$col};
876: # Replace '#' with the row number
877: $t{$lb}=~s/\#/$trow/g;
878: # Replace '....' with ','
879: $t{$lb}=~s/\.\.+/\,/g;
880: # Replace 'A0' with the value from 'A0'
881: $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
882: # Replace parameters
883: $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
884: }
1.78 matthew 885: }
1.104 matthew 886: # Deal with the normal cells
1.78 matthew 887: foreach (keys(%f)) {
1.112 matthew 888: if (exists($f{$_}) && ($_!~/template\_/)) {
1.42 www 889: my $matches=($_=~/^$pattern(\d+)/);
890: if (($matches) && ($1)) {
1.6 www 891: unless ($f{$_}=~/^\!/) {
892: $t{$_}=$c{$_};
893: }
894: } else {
895: $t{$_}=$f{$_};
1.7 www 896: $t{$_}=~s/\.\.+/\,/g;
1.104 matthew 897: $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
1.59 www 898: $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
1.6 www 899: }
1.1 www 900: }
1.78 matthew 901: }
1.104 matthew 902: # For inserted lines, [B-Z] is also valid
1.97 www 903: unless ($sheettype eq 'assesscalc') {
904: foreach (keys(%f)) {
905: if ($_=~/[B-Z](\d+)/) {
906: if ($f{'A'.$1}=~/^[\~\-]/) {
907: $t{$_}=$f{$_};
908: $t{$_}=~s/\.\.+/\,/g;
1.104 matthew 909: $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
1.97 www 910: $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
911: }
912: }
913: }
914: }
1.88 matthew 915: # For some reason 'A0' gets special treatment... This seems superfluous
916: # but I imagine it is here for a reason.
1.17 www 917: $t{'A0'}=$f{'A0'};
918: $t{'A0'}=~s/\.\.+/\,/g;
1.104 matthew 919: $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
1.59 www 920: $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
1.1 www 921: }
922:
1.124 matthew 923: sub calc {
924: undef %sheet_values;
925: &sett();
926: my $notfinished=1;
927: my $lastcalc='';
928: my $depth=0;
929: while ($notfinished) {
930: $notfinished=0;
931: foreach (keys(%t)) {
1.132 matthew 932: #$errorlog .= "$_:".$t{$_};
1.124 matthew 933: my $old=$sheet_values{$_};
934: $sheet_values{$_}=eval $t{$_};
935: if ($@) {
936: undef %sheet_values;
937: return $_.': '.$@;
938: }
939: if ($sheet_values{$_} ne $old) { $notfinished=1; $lastcalc=$_; }
1.132 matthew 940: #$errorlog .= ":".$sheet_values{$_}."\n";
1.124 matthew 941: }
942: $depth++;
943: if ($depth>100) {
944: undef %sheet_values;
945: return $lastcalc.': Maximum calculation depth exceeded';
946: }
947: }
948: return '';
949: }
950:
1.122 matthew 951: # ------------------------------------------- End of "Inside of the safe space"
952: ENDDEFS
953: $safeeval->reval($code);
954: return $safeeval;
955: }
956:
1.104 matthew 957: #
1.132 matthew 958: #
1.104 matthew 959: #
1.122 matthew 960: sub templaterow {
961: my $sheet = shift;
962: my @cols=();
1.132 matthew 963: my $rowlabel = 'Template';
1.122 matthew 964: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
965: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
966: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
967: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.132 matthew 968: push(@cols,{ name => 'template_'.$_,
1.151 ! matthew 969: formula => $sheet->{'f'}->{'template_'.$_},
! 970: value => $sheet->{'f'}->{'template_'.$_} });
1.122 matthew 971: }
1.132 matthew 972: return ($rowlabel,@cols);
1.122 matthew 973: }
974:
1.16 www 975: sub outrowassess {
1.104 matthew 976: # $n is the current row number
1.132 matthew 977: my ($sheet,$n) = @_;
1.6 www 978: my @cols=();
1.132 matthew 979: my $rowlabel='';
1.6 www 980: if ($n) {
1.122 matthew 981: my ($usy,$ufn)=split(/__&&&\__/,$sheet->{'f'}->{'A'.$n});
1.132 matthew 982: if (exists($sheet->{'rowlabel'}->{$usy})) {
983: $rowlabel = $sheet->{'rowlabel'}->{$usy};
1.104 matthew 984: } else {
1.132 matthew 985: $rowlabel = '';
1.104 matthew 986: }
1.6 www 987: } else {
1.132 matthew 988: $rowlabel = 'Export';
1.6 www 989: }
1.78 matthew 990: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
991: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
992: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
993: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.132 matthew 994: push(@cols,{ name => $_.$n,
1.151 ! matthew 995: formula => $sheet->{'f'}->{$_.$n},
1.132 matthew 996: value => $sheet->{'values'}->{$_.$n}});
1.78 matthew 997: }
1.132 matthew 998: return ($rowlabel,@cols);
1.6 www 999: }
1000:
1.18 www 1001: sub outrow {
1.132 matthew 1002: my ($sheet,$n)=@_;
1.18 www 1003: my @cols=();
1.132 matthew 1004: my $rowlabel;
1.18 www 1005: if ($n) {
1.132 matthew 1006: $rowlabel = $sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$n}};
1.18 www 1007: } else {
1.132 matthew 1008: if ($sheet->{'sheettype'} eq 'classcalc') {
1009: $rowlabel = 'Summary';
1010: } else {
1011: $rowlabel = 'Export';
1012: }
1.18 www 1013: }
1.78 matthew 1014: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1015: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
1016: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
1017: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.132 matthew 1018: push(@cols,{ name => $_.$n,
1.151 ! matthew 1019: formula => $sheet->{'f'}->{$_.$n},
1.132 matthew 1020: value => $sheet->{'values'}->{$_.$n}});
1.118 matthew 1021: }
1.132 matthew 1022: return ($rowlabel,@cols);
1.118 matthew 1023: }
1024:
1.4 www 1025: # ------------------------------------------------ Add or change formula values
1026: sub setformulas {
1.124 matthew 1027: my ($sheet)=shift;
1.119 matthew 1028: %{$sheet->{'safe'}->varglob('f')}=%{$sheet->{'f'}};
1.6 www 1029: }
1030:
1031: # ------------------------------------------------ Add or change formula values
1032: sub setconstants {
1.119 matthew 1033: my ($sheet)=shift;
1.122 matthew 1034: my ($constants) = @_;
1035: if (! ref($constants)) {
1036: my %tmp = @_;
1037: $constants = \%tmp;
1038: }
1039: $sheet->{'constants'} = $constants;
1.119 matthew 1040: return %{$sheet->{'safe'}->varglob('c')}=%{$sheet->{'constants'}};
1.6 www 1041: }
1042:
1.55 www 1043: # --------------------------------------------- Set names of other spreadsheets
1044: sub setothersheets {
1.119 matthew 1045: my $sheet = shift;
1046: my @othersheets = @_;
1047: $sheet->{'othersheets'} = \@othersheets;
1048: @{$sheet->{'safe'}->varglob('os')}=@othersheets;
1049: return;
1.55 www 1050: }
1051:
1.6 www 1052: # ------------------------------------------------ Add or change formula values
1053: sub setrowlabels {
1.119 matthew 1054: my $sheet=shift;
1.125 matthew 1055: my ($rowlabel) = @_;
1056: if (! ref($rowlabel)) {
1057: my %tmp = @_;
1058: $rowlabel = \%tmp;
1059: }
1060: $sheet->{'rowlabel'}=$rowlabel;
1.4 www 1061: }
1062:
1063: # ------------------------------------------------------- Calculate spreadsheet
1064: sub calcsheet {
1.119 matthew 1065: my $sheet=shift;
1.124 matthew 1066: my $result = $sheet->{'safe'}->reval('&calc();');
1067: %{$sheet->{'values'}} = %{$sheet->{'safe'}->varglob('sheet_values')};
1068: return $result;
1.4 www 1069: }
1070:
1071: # ---------------------------------------------------------------- Get formulas
1.131 matthew 1072: # Return a copy of the formulas
1.4 www 1073: sub getformulas {
1.119 matthew 1074: my $sheet = shift;
1075: return %{$sheet->{'safe'}->varglob('f')};
1.4 www 1076: }
1077:
1.132 matthew 1078: sub geterrorlog {
1079: my $sheet = shift;
1080: return ${$sheet->{'safe'}->varglob('errorlog')};
1081: }
1082:
1.139 matthew 1083: sub gettitle {
1084: my $sheet = shift;
1085: if ($sheet->{'sheettype'} eq 'classcalc') {
1086: return $sheet->{'coursedesc'};
1087: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1088: return 'Grades for '.$sheet->{'uname'}.'@'.$sheet->{'udom'};
1089: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1090: if (($sheet->{'usymb'} eq '_feedback') ||
1091: ($sheet->{'usymb'} eq '_evaluation') ||
1092: ($sheet->{'usymb'} eq '_discussion') ||
1093: ($sheet->{'usymb'} eq '_tutoring')) {
1094: my $title = $sheet->{'usymb'};
1095: $title =~ s/^_//;
1096: $title = ucfirst($title);
1097: return $title;
1098: }
1099: return if (! defined($sheet->{'mapid'}) ||
1100: $sheet->{'mapid'} !~ /^\d+$/);
1101: my $mapid = $sheet->{'mapid'};
1102: return if (! defined($sheet->{'resid'}) ||
1103: $sheet->{'resid'} !~ /^\d+$/);
1104: my $resid = $sheet->{'resid'};
1105: my %course_db;
1106: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
1107: &GDBM_READER(),0640);
1108: return if (! tied(%course_db));
1109: my $key = 'title_'.$mapid.'.'.$resid;
1110: my $title = '';
1111: if (exists($course_db{$key})) {
1112: $title = $course_db{$key};
1113: } else {
1114: $title = $sheet->{'usymb'};
1115: }
1116: untie (%course_db);
1117: return $title;
1118: }
1119: }
1120:
1.97 www 1121: # ----------------------------------------------------- Get value of $f{'A'.$n}
1122: sub getfa {
1.119 matthew 1123: my $sheet = shift;
1124: my ($n)=@_;
1125: return $sheet->{'safe'}->reval('$f{"A'.$n.'"}');
1.97 www 1126: }
1127:
1.14 www 1128: # ------------------------------------------------------------- Export of A-row
1.28 www 1129: sub exportdata {
1.119 matthew 1130: my $sheet=shift;
1.121 matthew 1131: my @exportarray=();
1132: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1133: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.130 matthew 1134: if (exists($sheet->{'values'}->{$_.'0'})) {
1135: push(@exportarray,$sheet->{'values'}->{$_.'0'});
1136: } else {
1137: push(@exportarray,'');
1138: }
1.121 matthew 1139: }
1140: return @exportarray;
1.14 www 1141: }
1.55 www 1142:
1.136 matthew 1143:
1144:
1145: sub update_student_sheet{
1.143 matthew 1146: my ($sheet,$r,$c) = @_;
1.136 matthew 1147: # Load in the studentcalc sheet
1148: &readsheet($sheet,'default_studentcalc');
1149: # Determine the structure (contained assessments, etc) of the sheet
1150: &updatesheet($sheet);
1151: # Load in the cached sheets for this student
1152: &cachedssheets($sheet);
1153: # Load in the (possibly cached) data from the assessment sheets
1.143 matthew 1154: &loadstudent($sheet,$r,$c);
1.136 matthew 1155: # Compute the sheet
1156: &calcsheet($sheet);
1157: }
1158:
1.5 www 1159: # ========================================================== End of Spreadsheet
1160: # =============================================================================
1.27 www 1161: #
1.135 matthew 1162: # Procedures for spreadsheet output
1.27 www 1163: #
1.6 www 1164: # --------------------------------------------- Produce output row n from sheet
1165:
1.132 matthew 1166: sub get_row {
1167: my ($sheet,$n) = @_;
1168: my ($rowlabel,@rowdata);
1.104 matthew 1169: if ($n eq '-') {
1.132 matthew 1170: ($rowlabel,@rowdata) = &templaterow($sheet);
1171: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1172: ($rowlabel,@rowdata) = &outrowassess($sheet,$n);
1.61 www 1173: } else {
1.132 matthew 1174: ($rowlabel,@rowdata) = &outrow($sheet,$n);
1.61 www 1175: }
1.132 matthew 1176: return ($rowlabel,@rowdata);
1.6 www 1177: }
1178:
1.132 matthew 1179: ########################################################################
1180: ########################################################################
1181: sub sort_indicies {
1182: my $sheet = shift;
1.142 matthew 1183: my @sortidx=();
1.106 matthew 1184: #
1.142 matthew 1185: if ($sheet->{'sheettype'} eq 'classcalc') {
1.143 matthew 1186: my @sortby=(undef);
1.142 matthew 1187: # Skip row 0
1188: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1189: my (undef,$sname,$sdom,$fullname,$section,$id) =
1190: split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
1191: push (@sortby, lc($fullname));
1192: push (@sortidx, $row);
1193: }
1194: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1195: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.143 matthew 1196: my @sortby1=(undef);
1197: my @sortby2=(undef);
1.142 matthew 1198: # Skip row 0
1199: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1200: my (undef,$symb,$uname,$udom,$mapid,$resid,$title) =
1201: split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
1202: $symb = &Apache::lonnet::unescape($symb);
1203: my ($sequence) = ($symb =~ /\/([^\/]*\.sequence)/);
1204: if ($sequence eq '') {
1205: $sequence = $symb;
1206: }
1.143 matthew 1207: push (@sortby1, $sequence);
1208: push (@sortby2, $title);
1.142 matthew 1209: push (@sortidx, $row);
1210: }
1.143 matthew 1211: @sortidx = sort { $sortby1[$a] cmp $sortby1[$b] ||
1212: $sortby2[$a] cmp $sortby2[$b] } @sortidx;
1.142 matthew 1213: } else {
1.143 matthew 1214: my @sortby=(undef);
1.142 matthew 1215: # Skip row 0
1216: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1217: push (@sortby, $sheet->{'safe'}->reval('$f{"A'.$row.'"}'));
1218: push (@sortidx, $row);
1219: }
1220: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1.65 www 1221: }
1.132 matthew 1222: return @sortidx;
1223: }
1224:
1.135 matthew 1225: #############################################################
1226: ### ###
1227: ### Spreadsheet Output Routines ###
1228: ### ###
1229: #############################################################
1230:
1231: ############################################
1232: ## HTML output routines ##
1233: ############################################
1.132 matthew 1234: sub html_editable_cell {
1235: my ($cell,$bgcolor) = @_;
1236: my $result;
1237: my ($name,$formula,$value);
1238: if (defined($cell)) {
1239: $name = $cell->{'name'};
1240: $formula = $cell->{'formula'};
1241: $value = $cell->{'value'};
1242: }
1243: $name = '' if (! defined($name));
1244: $formula = '' if (! defined($formula));
1245: if (! defined($value)) {
1246: $value = '<font color="'.$bgcolor.'">#</font>';
1247: if ($formula ne '') {
1248: $value = '<i>undefined value</i>';
1249: }
1250: }
1.133 matthew 1251: if ($value =~ /^\s*$/ ) {
1252: $value = '<font color="'.$bgcolor.'">#</font>';
1253: }
1.151 ! matthew 1254: &Apache::lonnet::logthis($name.' formula = '.$formula) if ($formula);
! 1255: $formula =~ s/</\</g;
! 1256: $formula =~ s/>/\>/g;
! 1257: $formula =~ s/\&/\&/g;
! 1258: $formula =~ s/\"/\"/g;
! 1259: $formula =~ s/\'/\"/g;
1.138 matthew 1260: $formula =~ s/\n/\\n/gs;
1.151 ! matthew 1261: &Apache::lonnet::logthis($name.' formula = '.$formula) if ($formula);
! 1262: $result .= "<a href=\"javascript:celledit(\'".
! 1263: $name."','".$formula."');\">".$value."</a>";
! 1264: &Apache::lonnet::logthis('result = '.$result) if ($formula);
1.132 matthew 1265: return $result;
1266: }
1267:
1268: sub html_uneditable_cell {
1269: my ($cell,$bgcolor) = @_;
1270: my $value = (defined($cell) ? $cell->{'value'} : '');
1271: return ' '.$value.' ';
1272: }
1273:
1274: sub outsheet_html {
1275: my ($sheet,$r) = @_;
1276: my ($num_uneditable,$realm,$row_type);
1.119 matthew 1277: if ($sheet->{'sheettype'} eq 'assesscalc') {
1.132 matthew 1278: $num_uneditable = 1;
1279: $realm = 'Assessment';
1280: $row_type = 'Item';
1.119 matthew 1281: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.132 matthew 1282: $num_uneditable = 26;
1283: $realm = 'User';
1284: $row_type = 'Assessment';
1285: } elsif ($sheet->{'sheettype'} eq 'classcalc') {
1286: $num_uneditable = 26;
1287: $realm = 'Course';
1288: $row_type = 'Student';
1289: } else {
1290: return; # error
1291: }
1292: ####################################
1293: # Print out header table
1294: ####################################
1295: my $num_left = 52-$num_uneditable;
1296: my $tabledata =<<"END";
1297: <table border="2">
1298: <tr>
1299: <th colspan="1" rowspan="2"><font size="+2">$realm</font></th>
1300: <td bgcolor="#FFDDDD" colspan="$num_uneditable">
1301: <b><font size="+1">Import</font></b></td>
1302: <td colspan="$num_left">
1303: <b><font size="+1">Calculations</font></b></td>
1304: </tr><tr>
1305: END
1306: my $label_num = 0;
1307: foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
1308: if ($label_num<$num_uneditable) {
1309: $tabledata.='<td bgcolor="#FFDDDD">';
1310: } else {
1311: $tabledata.='<td>';
1312: }
1313: $tabledata.="<b><font size=+1>$_</font></b></td>";
1314: $label_num++;
1.106 matthew 1315: }
1.132 matthew 1316: $tabledata.="</tr>\n";
1317: $r->print($tabledata);
1318: ####################################
1319: # Print out template row
1320: ####################################
1321: my ($rowlabel,@rowdata) = &get_row($sheet,'-');
1.149 matthew 1322: my $row_html = '<tr><td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1323: my $num_cols_output = 0;
1324: foreach my $cell (@rowdata) {
1325: if ($num_cols_output++ < $num_uneditable) {
1326: $row_html .= '<td bgcolor="#FFDDDD">';
1327: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
1328: } else {
1329: $row_html .= '<td bgcolor="#EOFFDD">';
1330: $row_html .= &html_editable_cell($cell,'#E0FFDD');
1331: }
1332: $row_html .= '</td>';
1333: }
1334: $row_html.= "</tr>\n";
1335: $r->print($row_html);
1336: ####################################
1337: # Print out summary/export row
1338: ####################################
1339: my ($rowlabel,@rowdata) = &get_row($sheet,'0');
1.149 matthew 1340: $row_html = '<tr><td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1341: $num_cols_output = 0;
1342: foreach my $cell (@rowdata) {
1343: if ($num_cols_output++ < 26) {
1344: $row_html .= '<td bgcolor="#CCCCFF">';
1345: $row_html .= &html_editable_cell($cell,'#CCCCFF');
1346: } else {
1347: $row_html .= '<td bgcolor="#DDCCFF">';
1348: $row_html .= &html_uneditable_cell(undef,'#CCCCFF');
1349: }
1350: $row_html .= '</td>';
1351: }
1352: $row_html.= "</tr>\n";
1353: $r->print($row_html);
1354: $r->print('</table>');
1355: ####################################
1356: # Prepare to output rows
1357: ####################################
1358: my @Rows = &sort_indicies($sheet);
1.106 matthew 1359: #
1360: # Loop through the rows and output them one at a time
1.132 matthew 1361: my $rows_output=0;
1362: foreach my $rownum (@Rows) {
1363: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1.136 matthew 1364: next if ($rowlabel =~ /^\s*$/);
1.141 matthew 1365: next if (($sheet->{'sheettype'} eq 'assesscalc') &&
1366: (! $ENV{'form.showall'}) &&
1367: ($rowdata[0]->{'value'} =~ /^\s*$/));
1.143 matthew 1368: if (! $ENV{'form.showall'} &&
1369: $sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
1.141 matthew 1370: my $row_is_empty = 1;
1371: foreach my $cell (@rowdata) {
1372: if ($cell->{'value'} !~ /^\s*$/) {
1373: $row_is_empty = 0;
1374: last;
1375: }
1376: }
1.143 matthew 1377: next if ($row_is_empty);
1.141 matthew 1378: }
1.132 matthew 1379: #
1380: my $defaultbg='#E0FF';
1381: #
1382: my $row_html ="\n".'<tr><td><b><font size=+1>'.$rownum.
1383: '</font></b></td>';
1384: #
1385: if ($sheet->{'sheettype'} eq 'classcalc') {
1.149 matthew 1386: $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1387: # Output links for each student?
1.133 matthew 1388: # Nope, that is already done for us in format_html_rowlabel (for now)
1.132 matthew 1389: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.149 matthew 1390: $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel);
1.132 matthew 1391: $row_html.= '<br>'.
1392: '<select name="sel_'.$rownum.'" '.
1393: 'onChange="changesheet('.$rownum.')">'.
1394: '<option name="default">Default</option>';
1395: foreach (@{$sheet->{'othersheets'}}) {
1396: $row_html.='<option name="'.$_.'"';
1397: #if ($ufn eq $_) {
1398: # $row_html.=' selected';
1399: #}
1400: $row_html.='>'.$_.'</option>';
1401: }
1402: $row_html.='</select></td>';
1403: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1.149 matthew 1404: $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1405: }
1406: #
1407: my $shown_cells = 0;
1408: foreach my $cell (@rowdata) {
1409: my $value = $cell->{'value'};
1410: my $formula = $cell->{'formula'};
1411: my $cellname = $cell->{'name'};
1412: #
1413: my $bgcolor;
1414: if ($shown_cells && ($shown_cells/5 == int($shown_cells/5))) {
1415: $bgcolor = $defaultbg.'99';
1416: } else {
1417: $bgcolor = $defaultbg.'DD';
1418: }
1419: $bgcolor='#FFDDDD' if ($shown_cells < $num_uneditable);
1420: #
1421: $row_html.='<td bgcolor='.$bgcolor.'>';
1422: if ($shown_cells < $num_uneditable) {
1423: $row_html .= &html_uneditable_cell($cell,$bgcolor);
1424: } else {
1425: $row_html .= &html_editable_cell($cell,$bgcolor);
1426: }
1427: $row_html.='</td>';
1428: $shown_cells++;
1429: }
1430: if ($row_html) {
1431: if ($rows_output % 25 == 0) {
1.102 matthew 1432: $r->print("</table>\n<br>\n");
1433: $r->rflush();
1.132 matthew 1434: $r->print('<table border=2>'.
1435: '<tr><td> <td>'.$row_type.'</td>'.
1436: '<td>'.
1.106 matthew 1437: join('</td><td>',
1438: (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
1439: 'abcdefghijklmnopqrstuvwxyz'))).
1.102 matthew 1440: "</td></tr>\n");
1441: }
1.132 matthew 1442: $rows_output++;
1443: $r->print($row_html);
1.78 matthew 1444: }
1.6 www 1445: }
1.132 matthew 1446: #
1447: $r->print('</table>');
1448: #
1449: # Debugging code (be sure to uncomment errorlog code in safe space):
1450: #
1451: # $r->print("\n<pre>");
1452: # $r->print(&geterrorlog($sheet));
1453: # $r->print("\n</pre>");
1454: return 1;
1455: }
1456:
1.135 matthew 1457: ############################################
1458: ## csv output routines ##
1459: ############################################
1.132 matthew 1460: sub outsheet_csv {
1461: my ($sheet,$r) = @_;
1.133 matthew 1462: my $csvdata = '';
1463: my @Values;
1464: ####################################
1465: # Prepare to output rows
1466: ####################################
1467: my @Rows = &sort_indicies($sheet);
1468: #
1469: # Loop through the rows and output them one at a time
1470: my $rows_output=0;
1471: foreach my $rownum (@Rows) {
1472: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1.136 matthew 1473: next if ($rowlabel =~ /^\s*$/);
1.149 matthew 1474: push (@Values,&format_csv_rowlabel($sheet,$rowlabel));
1.133 matthew 1475: foreach my $cell (@rowdata) {
1476: push (@Values,'"'.$cell->{'value'}.'"');
1477: }
1478: $csvdata.= join(',',@Values)."\n";
1479: @Values = ();
1480: }
1481: #
1.134 matthew 1482: # Write the CSV data to a file and serve up a link
1483: #
1484: my $filename = '/prtspool/'.
1485: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1486: time.'_'.rand(1000000000).'.csv';
1487: my $file;
1488: unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
1489: $r->log_error("Couldn't open $filename for output $!");
1490: $r->print("Problems occured in writing the csv file. ".
1491: "This error has been logged. ".
1492: "Please alert your LON-CAPA administrator.");
1493: $r->print("<pre>\n".$csvdata."</pre>\n");
1494: return 0;
1495: }
1496: print $file $csvdata;
1497: close($file);
1498: $r->print('<br /><br />'.
1499: '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
1.133 matthew 1500: #
1501: return 1;
1.132 matthew 1502: }
1503:
1.135 matthew 1504: ############################################
1505: ## Excel output routines ##
1506: ############################################
1507: sub outsheet_recursive_excel {
1508: my ($sheet,$r) = @_;
1.136 matthew 1509: my $c = $r->connection;
1.135 matthew 1510: return undef if ($sheet->{'sheettype'} ne 'classcalc');
1511: my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
1512: return undef if (! defined($workbook));
1513: #
1514: # Create main worksheet
1515: my $main_worksheet = $workbook->addworksheet('main');
1516: #
1517: # Figure out who the students are
1518: my %f=&getformulas($sheet);
1519: my $count = 0;
1.136 matthew 1520: $r->print(<<END);
1521: <p>
1522: Compiling Excel Workbook with a worksheet for each student.
1523: </p><p>
1524: This operation may take longer than a complete recalculation of the
1525: spreadsheet.
1526: </p><p>
1527: To abort this operation, hit the stop button on your browser.
1528: </p><p>
1529: A link to the spreadsheet will be available at the end of this process.
1530: </p>
1531: <p>
1532: END
1.135 matthew 1533: $r->rflush();
1.136 matthew 1534: my $starttime = time;
1.146 matthew 1535: foreach my $rownum (&sort_indicies($sheet)) {
1.135 matthew 1536: $count++;
1.146 matthew 1537: my ($sname,$sdom) = split(':',$f{'A'.$rownum});
1.135 matthew 1538: my $student_excel_worksheet=$workbook->addworksheet($sname.'@'.$sdom);
1539: # Create a new spreadsheet
1540: my $studentsheet = &makenewsheet($sname,$sdom,'studentcalc',undef);
1541: # Read in the spreadsheet definition
1.143 matthew 1542: &update_student_sheet($studentsheet,$r,$c);
1.135 matthew 1543: # Stuff the sheet into excel
1544: &export_sheet_as_excel($studentsheet,$student_excel_worksheet);
1.136 matthew 1545: my $totaltime = int((time - $starttime) / $count * $sheet->{'maxrow'});
1546: my $timeleft = int((time - $starttime) / $count * ($sheet->{'maxrow'} - $count));
1.135 matthew 1547: if ($count % 5 == 0) {
1.136 matthew 1548: $r->print($count.' students completed.'.
1549: ' Time remaining: '.$timeleft.' sec. '.
1550: ' Estimated total time: '.$totaltime." sec <br />\n");
1.135 matthew 1551: $r->rflush();
1552: }
1.136 matthew 1553: if(defined($c) && ($c->aborted())) {
1554: last;
1555: }
1.135 matthew 1556: }
1557: #
1.136 matthew 1558: if(! $c->aborted() ) {
1559: $r->print('All students spreadsheets completed!<br />');
1560: $r->rflush();
1561: #
1562: # &export_sheet_as_excel fills $worksheet with the data from $sheet
1563: &export_sheet_as_excel($sheet,$main_worksheet);
1564: #
1565: $workbook->close();
1566: # Okay, the spreadsheet is taken care of, so give the user a link.
1567: $r->print('<br /><br />'.
1568: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1569: } else {
1570: $workbook->close(); # Not sure how necessary this is.
1571: #unlink('/home/httpd'.$filename); # No need to keep this around?
1572: }
1.135 matthew 1573: return 1;
1574: }
1575:
1.132 matthew 1576: sub outsheet_excel {
1577: my ($sheet,$r) = @_;
1.135 matthew 1578: my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
1579: return undef if (! defined($workbook));
1580: my $sheetname;
1581: if ($sheet->{'sheettype'} eq 'classcalc') {
1582: $sheetname = 'Main';
1583: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1584: $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'};
1585: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1586: $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'}.' assessment';
1587: }
1588: my $worksheet = $workbook->addworksheet($sheetname);
1589: #
1590: # &export_sheet_as_excel fills $worksheet with the data from $sheet
1591: &export_sheet_as_excel($sheet,$worksheet);
1592: #
1593: $workbook->close();
1594: # Okay, the spreadsheet is taken care of, so give the user a link.
1595: $r->print('<br /><br />'.
1596: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1597: return 1;
1598: }
1599:
1600: sub create_excel_spreadsheet {
1601: my ($sheet,$r) = @_;
1.134 matthew 1602: my $filename = '/prtspool/'.
1603: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1604: time.'_'.rand(1000000000).'.xls';
1605: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1606: if (! defined($workbook)) {
1607: $r->log_error("Error creating excel spreadsheet $filename: $!");
1608: $r->print("Problems creating new Excel file. ".
1609: "This error has been logged. ".
1610: "Please alert your LON-CAPA administrator");
1.135 matthew 1611: return undef;
1.134 matthew 1612: }
1613: #
1614: # The spreadsheet stores temporary data in files, then put them
1615: # together. If needed we should be able to disable this (memory only).
1616: # The temporary directory must be specified before calling 'addworksheet'.
1617: # File::Temp is used to determine the temporary directory.
1618: $workbook->set_tempdir('/home/httpd/perl/tmp');
1619: #
1620: # Determine the name to give the worksheet
1.135 matthew 1621: return ($workbook,$filename);
1622: }
1623:
1624: sub export_sheet_as_excel {
1625: my $sheet = shift;
1626: my $worksheet = shift;
1.139 matthew 1627: #
1628: my $rows_output = 0;
1629: my $cols_output = 0;
1630: ####################################
1631: # Write an identifying row #
1632: ####################################
1633: my @Headerinfo = ($sheet->{'coursedesc'});
1634: my $title = &gettitle($sheet);
1635: $cols_output = 0;
1636: if (defined($title)) {
1637: $worksheet->write($rows_output++,$cols_output++,$title);
1638: }
1639: ####################################
1640: # Write the summary/export row #
1641: ####################################
1642: my ($rowlabel,@rowdata) = &get_row($sheet,'0');
1.149 matthew 1643: my $label = &format_excel_rowlabel($sheet,$rowlabel);
1.139 matthew 1644: $cols_output = 0;
1645: $worksheet->write($rows_output,$cols_output++,$label);
1646: foreach my $cell (@rowdata) {
1647: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1648: }
1649: $rows_output+= 2; # Skip a row, just for fun
1.134 matthew 1650: ####################################
1651: # Prepare to output rows
1652: ####################################
1653: my @Rows = &sort_indicies($sheet);
1654: #
1655: # Loop through the rows and output them one at a time
1656: foreach my $rownum (@Rows) {
1657: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1.143 matthew 1658: next if ($rowlabel =~ /^[\s]*$/);
1.139 matthew 1659: $cols_output = 0;
1.149 matthew 1660: my $label = &format_excel_rowlabel($sheet,$rowlabel);
1.143 matthew 1661: if ( ! $ENV{'form.showall'} &&
1662: $sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
1663: my $row_is_empty = 1;
1664: foreach my $cell (@rowdata) {
1665: if ($cell->{'value'} !~ /^\s*$/) {
1666: $row_is_empty = 0;
1667: last;
1668: }
1669: }
1670: next if ($row_is_empty);
1671: }
1.134 matthew 1672: $worksheet->write($rows_output,$cols_output++,$label);
1673: if (ref($label)) {
1674: $cols_output = (scalar(@$label));
1675: }
1676: foreach my $cell (@rowdata) {
1.139 matthew 1677: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1.134 matthew 1678: }
1679: $rows_output++;
1680: }
1.135 matthew 1681: return;
1.132 matthew 1682: }
1683:
1.135 matthew 1684: ############################################
1685: ## XML output routines ##
1686: ############################################
1.132 matthew 1687: sub outsheet_xml {
1688: my ($sheet,$r) = @_;
1.135 matthew 1689: ## Someday XML
1690: ## Will be rendered for the user
1691: ## But not on this day
1.6 www 1692: }
1693:
1.135 matthew 1694: ##
1695: ## Outsheet - calls other outsheet_* functions
1696: ##
1.132 matthew 1697: sub outsheet {
1.143 matthew 1698: my ($sheet,$r)=@_;
1.134 matthew 1699: if (! exists($ENV{'form.output'})) {
1700: $ENV{'form.output'} = 'HTML';
1701: }
1702: if (lc($ENV{'form.output'}) eq 'csv') {
1.133 matthew 1703: &outsheet_csv($sheet,$r);
1.134 matthew 1704: } elsif (lc($ENV{'form.output'}) eq 'excel') {
1705: &outsheet_excel($sheet,$r);
1.135 matthew 1706: } elsif (lc($ENV{'form.output'}) eq 'recursive excel') {
1707: &outsheet_recursive_excel($sheet,$r);
1.134 matthew 1708: # } elsif (lc($ENV{'form.output'}) eq 'xml' ) {
1.132 matthew 1709: # &outsheet_xml($sheet,$r);
1.133 matthew 1710: } else {
1711: &outsheet_html($sheet,$r);
1712: }
1.132 matthew 1713: }
1714:
1715: ########################################################################
1716: ########################################################################
1.55 www 1717: sub othersheets {
1.119 matthew 1718: my ($sheet,$stype)=@_;
1719: $stype = $sheet->{'sheettype'} if (! defined($stype));
1.81 matthew 1720: #
1.119 matthew 1721: my $cnum = $sheet->{'cnum'};
1722: my $cdom = $sheet->{'cdom'};
1723: my $chome = $sheet->{'chome'};
1.81 matthew 1724: #
1.55 www 1725: my @alternatives=();
1.81 matthew 1726: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
1727: my ($tmp) = keys(%results);
1728: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1729: @alternatives = sort (keys(%results));
1730: }
1.55 www 1731: return @alternatives;
1732: }
1733:
1.82 matthew 1734: #
1735: # -------------------------------------- Parse a spreadsheet
1736: #
1737: sub parse_sheet {
1738: # $sheetxml is a scalar reference or a scalar
1739: my ($sheetxml) = @_;
1740: if (! ref($sheetxml)) {
1741: my $tmp = $sheetxml;
1742: $sheetxml = \$tmp;
1743: }
1744: my %f;
1745: my $parser=HTML::TokeParser->new($sheetxml);
1746: my $token;
1747: while ($token=$parser->get_token) {
1748: if ($token->[0] eq 'S') {
1749: if ($token->[1] eq 'field') {
1750: $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
1751: $parser->get_text('/field');
1752: }
1753: if ($token->[1] eq 'template') {
1754: $f{'template_'.$token->[2]->{'col'}}=
1755: $parser->get_text('/template');
1756: }
1757: }
1758: }
1759: return \%f;
1760: }
1761:
1.55 www 1762: #
1.27 www 1763: # -------------------------------------- Read spreadsheet formulas for a course
1764: #
1765: sub readsheet {
1.119 matthew 1766: my ($sheet,$fn)=@_;
1.107 matthew 1767: #
1.119 matthew 1768: my $stype = $sheet->{'sheettype'};
1769: my $cnum = $sheet->{'cnum'};
1770: my $cdom = $sheet->{'cdom'};
1771: my $chome = $sheet->{'chome'};
1.107 matthew 1772: #
1.104 matthew 1773: if (! defined($fn)) {
1774: # There is no filename. Look for defaults in course and global, cache
1775: unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
1776: my %tmphash = &Apache::lonnet::get('environment',
1777: ['spreadsheet_default_'.$stype],
1778: $cdom,$cnum);
1779: my ($tmp) = keys(%tmphash);
1780: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1781: $fn = 'default_'.$stype;
1782: } else {
1783: $fn = $tmphash{'spreadsheet_default_'.$stype};
1784: }
1785: unless (($fn) && ($fn!~/^error\:/)) {
1786: $fn='default_'.$stype;
1787: }
1788: $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn;
1789: }
1790: }
1791: # $fn now has a value
1.119 matthew 1792: $sheet->{'filename'} = $fn;
1.104 matthew 1793: # see if sheet is cached
1794: my $fstring='';
1795: if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
1.119 matthew 1796: my %tmp = split(/___;___/,$fstring);
1.124 matthew 1797: $sheet->{'f'} = \%tmp;
1798: &setformulas($sheet);
1.104 matthew 1799: } else {
1800: # Not cached, need to read
1801: my %f=();
1802: if ($fn=~/^default\_/) {
1803: my $sheetxml='';
1804: my $fh;
1805: my $dfn=$fn;
1806: $dfn=~s/\_/\./g;
1807: if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
1808: $sheetxml=join('',<$fh>);
1809: } else {
1.141 matthew 1810: # $sheetxml='<field row="0" col="A">"Error"</field>';
1811: $sheetxml='<field row="0" col="A"></field>';
1.104 matthew 1812: }
1813: %f=%{&parse_sheet(\$sheetxml)};
1814: } elsif($fn=~/\/*\.spreadsheet$/) {
1815: my $sheetxml=&Apache::lonnet::getfile
1816: (&Apache::lonnet::filelocation('',$fn));
1817: if ($sheetxml == -1) {
1818: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
1819: .$fn.'"</field>';
1820: }
1821: %f=%{&parse_sheet(\$sheetxml)};
1822: } else {
1823: my $sheet='';
1824: my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
1825: my ($tmp) = keys(%tmphash);
1826: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1827: foreach (keys(%tmphash)) {
1828: $f{$_}=$tmphash{$_};
1829: }
1830: }
1831: }
1832: # Cache and set
1833: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1.124 matthew 1834: $sheet->{'f'}=\%f;
1835: &setformulas($sheet);
1.3 www 1836: }
1837: }
1838:
1.28 www 1839: # -------------------------------------------------------- Make new spreadsheet
1840: sub makenewsheet {
1841: my ($uname,$udom,$stype,$usymb)=@_;
1.119 matthew 1842: my $sheet={};
1843: $sheet->{'uname'} = $uname;
1844: $sheet->{'udom'} = $udom;
1845: $sheet->{'sheettype'} = $stype;
1846: $sheet->{'usymb'} = $usymb;
1.139 matthew 1847: $sheet->{'mapid'} = $ENV{'form.mapid'};
1848: $sheet->{'resid'} = $ENV{'form.resid'};
1.119 matthew 1849: $sheet->{'cid'} = $ENV{'request.course.id'};
1850: $sheet->{'csec'} = $Section{$uname.':'.$udom};
1851: $sheet->{'coursefilename'} = $ENV{'request.course.fn'};
1852: $sheet->{'cnum'} = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1853: $sheet->{'cdom'} = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1854: $sheet->{'chome'} = $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.134 matthew 1855: $sheet->{'coursedesc'} = $ENV{'course.'.$ENV{'request.course.id'}.
1.139 matthew 1856: '.description'};
1.119 matthew 1857: $sheet->{'uhome'} = &Apache::lonnet::homeserver($uname,$udom);
1858: #
1859: #
1860: $sheet->{'f'} = {};
1861: $sheet->{'constants'} = {};
1862: $sheet->{'othersheets'} = [];
1863: $sheet->{'rowlabel'} = {};
1864: #
1865: #
1866: $sheet->{'safe'}=&initsheet($sheet->{'sheettype'});
1.116 matthew 1867: #
1.119 matthew 1868: # Place all the %$sheet items into the safe space except the safe space
1869: # itself
1.105 matthew 1870: my $initstring = '';
1.119 matthew 1871: foreach (qw/uname udom sheettype usymb cid csec coursefilename
1872: cnum cdom chome uhome/) {
1873: $initstring.= qq{\$$_="$sheet->{$_}";};
1.105 matthew 1874: }
1.119 matthew 1875: $sheet->{'safe'}->reval($initstring);
1876: return $sheet;
1.28 www 1877: }
1878:
1.19 www 1879: # ------------------------------------------------------------ Save spreadsheet
1880: sub writesheet {
1.119 matthew 1881: my ($sheet,$makedef)=@_;
1882: my $cid=$sheet->{'cid'};
1.104 matthew 1883: if (&Apache::lonnet::allowed('opa',$cid)) {
1.119 matthew 1884: my %f=&getformulas($sheet);
1885: my $stype= $sheet->{'sheettype'};
1886: my $cnum = $sheet->{'cnum'};
1887: my $cdom = $sheet->{'cdom'};
1888: my $chome= $sheet->{'chome'};
1889: my $fn = $sheet->{'filename'};
1.104 matthew 1890: # Cache new sheet
1891: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1892: # Write sheet
1893: foreach (keys(%f)) {
1.131 matthew 1894: delete($f{$_}) if ($f{$_} eq 'import');
1.104 matthew 1895: }
1.131 matthew 1896: my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
1.104 matthew 1897: if ($reply eq 'ok') {
1.131 matthew 1898: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
1899: {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
1900: $cdom,$cnum);
1.104 matthew 1901: if ($reply eq 'ok') {
1902: if ($makedef) {
1.131 matthew 1903: return &Apache::lonnet::put('environment',
1904: {'spreadsheet_default_'.$stype => $fn },
1905: $cdom,$cnum);
1.104 matthew 1906: }
1907: return $reply;
1908: }
1909: return $reply;
1910: }
1911: return $reply;
1912: }
1913: return 'unauthorized';
1.19 www 1914: }
1915:
1.10 www 1916: # ----------------------------------------------- Make a temp copy of the sheet
1.28 www 1917: # "Modified workcopy" - interactive only
1918: #
1.10 www 1919: sub tmpwrite {
1.119 matthew 1920: my ($sheet) = @_;
1.28 www 1921: my $fn=$ENV{'user.name'}.'_'.
1.119 matthew 1922: $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
1923: $sheet->{'filename'};
1.10 www 1924: $fn=~s/\W/\_/g;
1925: $fn=$tmpdir.$fn.'.tmp';
1926: my $fh;
1927: if ($fh=Apache::File->new('>'.$fn)) {
1.119 matthew 1928: print $fh join("\n",&getformulas($sheet));
1.10 www 1929: }
1930: }
1931:
1932: # ---------------------------------------------------------- Read the temp copy
1933: sub tmpread {
1.119 matthew 1934: my ($sheet,$nfield,$nform)=@_;
1.28 www 1935: my $fn=$ENV{'user.name'}.'_'.
1.119 matthew 1936: $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
1937: $sheet->{'filename'};
1.10 www 1938: $fn=~s/\W/\_/g;
1939: $fn=$tmpdir.$fn.'.tmp';
1940: my $fh;
1941: my %fo=();
1.92 www 1942: my $countrows=0;
1.10 www 1943: if ($fh=Apache::File->new($fn)) {
1944: my $name;
1945: while ($name=<$fh>) {
1946: chomp($name);
1947: my $value=<$fh>;
1948: chomp($value);
1949: $fo{$name}=$value;
1.93 www 1950: if ($name=~/^A(\d+)$/) {
1951: if ($1>$countrows) {
1952: $countrows=$1;
1953: }
1954: }
1.10 www 1955: }
1956: }
1.55 www 1957: if ($nform eq 'changesheet') {
1.128 matthew 1958: $fo{'A'.$nfield}=(split(/__&&&\__/,$fo{'A'.$nfield}))[0];
1.55 www 1959: unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
1.57 www 1960: $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
1.55 www 1961: }
1.92 www 1962: } elsif ($nfield eq 'insertrow') {
1.93 www 1963: $countrows++;
1.95 www 1964: my $newrow=substr('000000'.$countrows,-7);
1.92 www 1965: if ($nform eq 'top') {
1.94 www 1966: $fo{'A'.$countrows}='--- '.$newrow;
1.92 www 1967: } else {
1.94 www 1968: $fo{'A'.$countrows}='~~~ '.$newrow;
1.92 www 1969: }
1.55 www 1970: } else {
1971: if ($nfield) { $fo{$nfield}=$nform; }
1972: }
1.124 matthew 1973: $sheet->{'f'}=\%fo;
1974: &setformulas($sheet);
1.10 www 1975: }
1976:
1.104 matthew 1977: ##################################################
1978: ##################################################
1.11 www 1979:
1.104 matthew 1980: =pod
1.11 www 1981:
1.104 matthew 1982: =item &parmval()
1.11 www 1983:
1.104 matthew 1984: Determine the value of a parameter.
1.11 www 1985:
1.119 matthew 1986: Inputs: $what, the parameter needed, $sheet, the safe space
1.11 www 1987:
1.104 matthew 1988: Returns: The value of a parameter, or '' if none.
1.11 www 1989:
1.104 matthew 1990: This function cascades through the possible levels searching for a value for
1991: a parameter. The levels are checked in the following order:
1992: user, course (at section level and course level), map, and lonnet::metadata.
1993: This function uses %parmhash, which must be tied prior to calling it.
1994: This function also requires %courseopt and %useropt to be initialized for
1995: this user and course.
1.11 www 1996:
1.104 matthew 1997: =cut
1.11 www 1998:
1.104 matthew 1999: ##################################################
2000: ##################################################
2001: sub parmval {
1.119 matthew 2002: my ($what,$sheet)=@_;
2003: my $symb = $sheet->{'usymb'};
1.104 matthew 2004: unless ($symb) { return ''; }
2005: #
1.119 matthew 2006: my $cid = $sheet->{'cid'};
2007: my $csec = $sheet->{'csec'};
2008: my $uname = $sheet->{'uname'};
2009: my $udom = $sheet->{'udom'};
1.104 matthew 2010: my $result='';
2011: #
2012: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
2013: # Cascading lookup scheme
2014: my $rwhat=$what;
2015: $what =~ s/^parameter\_//;
2016: $what =~ s/\_([^\_]+)$/\.$1/;
2017: #
2018: my $symbparm = $symb.'.'.$what;
2019: my $mapparm = $mapname.'___(all).'.$what;
2020: my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
2021: #
2022: my $seclevel = $usercourseprefix.'.['.$csec.'].'.$what;
2023: my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
2024: my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
2025: #
2026: my $courselevel = $usercourseprefix.'.'.$what;
2027: my $courselevelr = $usercourseprefix.'.'.$symbparm;
2028: my $courselevelm = $usercourseprefix.'.'.$mapparm;
2029: # fourth, check user
1.115 albertel 2030: if (defined($uname)) {
2031: return $useropt{$courselevelr} if (defined($useropt{$courselevelr}));
2032: return $useropt{$courselevelm} if (defined($useropt{$courselevelm}));
2033: return $useropt{$courselevel} if (defined($useropt{$courselevel}));
1.104 matthew 2034: }
2035: # third, check course
1.115 albertel 2036: if (defined($csec)) {
2037: return $courseopt{$seclevelr} if (defined($courseopt{$seclevelr}));
2038: return $courseopt{$seclevelm} if (defined($courseopt{$seclevelm}));
2039: return $courseopt{$seclevel} if (defined($courseopt{$seclevel}));
1.104 matthew 2040: }
2041: #
1.115 albertel 2042: return $courseopt{$courselevelr} if (defined($courseopt{$courselevelr}));
2043: return $courseopt{$courselevelm} if (defined($courseopt{$courselevelm}));
2044: return $courseopt{$courselevel} if (defined($courseopt{$courselevel}));
1.104 matthew 2045: # second, check map parms
2046: my $thisparm = $parmhash{$symbparm};
1.115 albertel 2047: return $thisparm if (defined($thisparm));
1.104 matthew 2048: # first, check default
2049: return &Apache::lonnet::metadata($fn,$rwhat.'.default');
1.11 www 2050: }
2051:
1.133 matthew 2052:
2053: ##################################################################
2054: ## Row label formatting routines ##
2055: ##################################################################
2056: sub format_html_rowlabel {
1.149 matthew 2057: my $sheet = shift;
1.133 matthew 2058: my $rowlabel = shift;
2059: return '' if ($rowlabel eq '');
2060: my ($type,$labeldata) = split(':',$rowlabel,2);
2061: my $result = '';
2062: if ($type eq 'symb') {
1.149 matthew 2063: my ($symb,$mapid,$resid,$title) = split(':',$labeldata);
1.133 matthew 2064: $symb = &Apache::lonnet::unescape($symb);
2065: $result = '<a href="/adm/assesscalc?usymb='.$symb.
1.149 matthew 2066: '&uname='.$sheet->{'uname'}.'&udom='.$sheet->{'udom'}.
1.139 matthew 2067: '&mapid='.$mapid.'&resid='.$resid.'">'.$title.'</a>';
1.133 matthew 2068: } elsif ($type eq 'student') {
2069: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
1.148 matthew 2070: if ($fullname =~ /^\s*$/) {
2071: $fullname = $sname.'@'.$sdom;
2072: }
1.133 matthew 2073: $result ='<a href="/adm/studentcalc?uname='.$sname.
2074: '&udom='.$sdom.'">';
2075: $result.=$section.' '.$id." ".$fullname.'</a>';
2076: } elsif ($type eq 'parameter') {
2077: $result = $labeldata;
2078: } else {
2079: $result = '<b><font size=+1>'.$rowlabel.'</font></b>';
2080: }
2081: return $result;
2082: }
2083:
2084: sub format_csv_rowlabel {
1.149 matthew 2085: my $sheet = shift;
1.133 matthew 2086: my $rowlabel = shift;
2087: return '' if ($rowlabel eq '');
2088: my ($type,$labeldata) = split(':',$rowlabel,2);
2089: my $result = '';
2090: if ($type eq 'symb') {
1.149 matthew 2091: my ($symb,$mapid,$resid,$title) = split(':',$labeldata);
1.133 matthew 2092: $symb = &Apache::lonnet::unescape($symb);
2093: $result = $title;
2094: } elsif ($type eq 'student') {
2095: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2096: $result = join('","',($sname,$sdom,$fullname,$section,$id));
2097: } elsif ($type eq 'parameter') {
2098: $labeldata =~ s/<br>/ /g;
2099: $result = $labeldata;
2100: } else {
2101: $result = $rowlabel;
2102: }
2103: return '"'.$result.'"';
2104: }
2105:
1.134 matthew 2106: sub format_excel_rowlabel {
1.149 matthew 2107: my $sheet = shift;
1.125 matthew 2108: my $rowlabel = shift;
1.132 matthew 2109: return '' if ($rowlabel eq '');
1.125 matthew 2110: my ($type,$labeldata) = split(':',$rowlabel,2);
2111: my $result = '';
2112: if ($type eq 'symb') {
1.149 matthew 2113: my ($symb,$mapid,$resid,$title) = split(':',$labeldata);
1.125 matthew 2114: $symb = &Apache::lonnet::unescape($symb);
1.133 matthew 2115: $result = $title;
1.125 matthew 2116: } elsif ($type eq 'student') {
2117: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
1.134 matthew 2118: $section = '' if (! defined($section));
2119: $id = '' if (! defined($id));
2120: my @Data = ($sname,$sdom,$fullname,$section,$id);
2121: $result = \@Data;
1.125 matthew 2122: } elsif ($type eq 'parameter') {
1.133 matthew 2123: $labeldata =~ s/<br>/ /g;
1.127 matthew 2124: $result = $labeldata;
1.125 matthew 2125: } else {
1.133 matthew 2126: $result = $rowlabel;
1.125 matthew 2127: }
2128: return $result;
2129: }
2130:
1.23 www 2131: # ---------------------------------------------- Update rows for course listing
1.28 www 2132: sub updateclasssheet {
1.119 matthew 2133: my ($sheet) = @_;
2134: my $cnum =$sheet->{'cnum'};
2135: my $cdom =$sheet->{'cdom'};
2136: my $cid =$sheet->{'cid'};
2137: my $chome =$sheet->{'chome'};
1.102 matthew 2138: #
1.113 matthew 2139: %Section = ();
2140: #
1.102 matthew 2141: # Read class list and row labels
1.118 matthew 2142: my $classlist = &Apache::loncoursedata::get_classlist();
2143: if (! defined($classlist)) {
2144: return 'Could not access course classlist';
2145: }
1.102 matthew 2146: #
1.23 www 2147: my %currentlist=();
1.118 matthew 2148: foreach my $student (keys(%$classlist)) {
2149: my ($studentDomain,$studentName,$end,$start,$id,$studentSection,
2150: $fullname,$status) = @{$classlist->{$student}};
1.139 matthew 2151: $Section{$studentName.':'.$studentDomain} = $studentSection;
1.118 matthew 2152: if ($ENV{'form.Status'} eq $status || $ENV{'form.Status'} eq 'Any') {
1.125 matthew 2153: $currentlist{$student}=join(':',('student',$studentName,
2154: $studentDomain,$fullname,
2155: $studentSection,$id));
1.118 matthew 2156: }
2157: }
1.102 matthew 2158: #
2159: # Find discrepancies between the course row table and this
2160: #
1.119 matthew 2161: my %f=&getformulas($sheet);
1.102 matthew 2162: my $changed=0;
2163: #
1.119 matthew 2164: $sheet->{'maxrow'}=0;
1.102 matthew 2165: my %existing=();
2166: #
2167: # Now obsolete rows
2168: foreach (keys(%f)) {
2169: if ($_=~/^A(\d+)/) {
1.119 matthew 2170: if ($1 > $sheet->{'maxrow'}) {
2171: $sheet->{'maxrow'}= $1;
2172: }
1.102 matthew 2173: $existing{$f{$_}}=1;
2174: unless ((defined($currentlist{$f{$_}})) || (!$1) ||
1.120 matthew 2175: ($f{$_}=~/^(~~~|---)/)) {
1.102 matthew 2176: $f{$_}='!!! Obsolete';
2177: $changed=1;
1.23 www 2178: }
1.78 matthew 2179: }
1.102 matthew 2180: }
2181: #
2182: # New and unknown keys
1.128 matthew 2183: foreach my $student (sort keys(%currentlist)) {
2184: unless ($existing{$student}) {
1.102 matthew 2185: $changed=1;
1.119 matthew 2186: $sheet->{'maxrow'}++;
1.128 matthew 2187: $f{'A'.$sheet->{'maxrow'}}=$student;
1.78 matthew 2188: }
1.23 www 2189: }
1.119 matthew 2190: if ($changed) {
1.124 matthew 2191: $sheet->{'f'} = \%f;
2192: &setformulas($sheet,%f);
1.119 matthew 2193: }
1.102 matthew 2194: #
1.125 matthew 2195: &setrowlabels($sheet,\%currentlist);
1.23 www 2196: }
1.5 www 2197:
1.28 www 2198: # ----------------------------------- Update rows for student and assess sheets
1.136 matthew 2199: sub get_student_rowlabels {
2200: my ($sheet) = @_;
2201: #
2202: my %course_db;
2203: #
2204: my $stype = $sheet->{'sheettype'};
2205: my $uname = $sheet->{'uname'};
2206: my $udom = $sheet->{'udom'};
2207: #
2208: $sheet->{'rowlabel'} = {};
2209: #
2210: my $identifier =$sheet->{'coursefilename'}.'_'.$stype;
2211: if ($rowlabel_cache{$identifier}) {
2212: %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
2213: } else {
2214: # Get the data and store it in the cache
2215: # Tie hash
2216: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
2217: &GDBM_READER(),0640);
2218: if (! tied(%course_db)) {
2219: return 'Could not access course data';
2220: }
2221: #
2222: my %assesslist;
2223: foreach ('Feedback','Evaluation','Tutoring','Discussion') {
2224: my $symb = '_'.lc($_);
1.149 matthew 2225: $assesslist{$symb} = join(':',('symb',$symb,0,0,$_));
1.136 matthew 2226: }
2227: #
2228: while (my ($key,$srcf) = each(%course_db)) {
2229: next if ($key !~ /^src_(\d+)\.(\d+)$/);
2230: my $mapid = $1;
2231: my $resid = $2;
2232: my $id = $mapid.'.'.$resid;
2233: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
2234: my $symb=
2235: &Apache::lonnet::declutter($course_db{'map_id_'.$mapid}).
2236: '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
2237: $assesslist{$symb}='symb:'.&Apache::lonnet::escape($symb).':'
1.149 matthew 2238: .$mapid.':'.$resid.':'.$course_db{'title_'.$id};
1.136 matthew 2239: }
2240: }
2241: untie(%course_db);
2242: # Store away the data
2243: $sheet->{'rowlabel'} = \%assesslist;
2244: $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
2245: }
2246:
2247: }
2248:
2249: sub get_assess_rowlabels {
1.119 matthew 2250: my ($sheet) = @_;
1.128 matthew 2251: #
1.136 matthew 2252: my %course_db;
1.128 matthew 2253: #
2254: my $stype = $sheet->{'sheettype'};
2255: my $uname = $sheet->{'uname'};
2256: my $udom = $sheet->{'udom'};
1.136 matthew 2257: my $usymb = $sheet->{'usymb'};
2258: #
1.119 matthew 2259: $sheet->{'rowlabel'} = {};
1.136 matthew 2260: my $identifier =$sheet->{'coursefilename'}.'_'.$stype.'_'.$usymb;
2261: #
2262: if ($rowlabel_cache{$identifier}) {
2263: %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
1.104 matthew 2264: } else {
1.136 matthew 2265: # Get the data and store it in the cache
1.104 matthew 2266: # Tie hash
1.136 matthew 2267: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
1.104 matthew 2268: &GDBM_READER(),0640);
1.136 matthew 2269: if (! tied(%course_db)) {
1.104 matthew 2270: return 'Could not access course data';
2271: }
1.125 matthew 2272: #
1.128 matthew 2273: my %parameter_labels=
2274: ('timestamp' =>
2275: 'parameter:Timestamp of Last Transaction<br>timestamp',
2276: 'subnumber' =>
2277: 'parameter:Number of Submissions<br>subnumber',
2278: 'tutornumber' =>
2279: 'parameter:Number of Tutor Responses<br>tutornumber',
2280: 'totalpoints' =>
2281: 'parameter:Total Points Granted<br>totalpoints');
1.136 matthew 2282: while (my ($key,$srcf) = each(%course_db)) {
2283: next if ($key !~ /^src_(\d+)\.(\d+)$/);
2284: my $mapid = $1;
2285: my $resid = $2;
2286: my $id = $mapid.'.'.$resid;
1.104 matthew 2287: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
1.136 matthew 2288: # Loop through the metadata for this key
2289: my @Metadata = split(/,/,
2290: &Apache::lonnet::metadata($srcf,'keys'));
2291: foreach my $key (@Metadata) {
1.104 matthew 2292: next if ($key !~ /^(stores|parameter)_/);
2293: my $display=
2294: &Apache::lonnet::metadata($srcf,$key.'.display');
2295: unless ($display) {
2296: $display.=
2297: &Apache::lonnet::metadata($srcf,$key.'.name');
2298: }
2299: $display.='<br>'.$key;
1.128 matthew 2300: $parameter_labels{$key}='parameter:'.$display;
1.104 matthew 2301: } # end of foreach
2302: }
1.136 matthew 2303: }
2304: untie(%course_db);
2305: # Store away the results
2306: $sheet->{'rowlabel'} = \%parameter_labels;
2307: $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
2308: }
2309:
2310: }
2311:
2312: sub updatestudentassesssheet {
2313: my $sheet = shift;
2314: if ($sheet->{'sheettype'} eq 'studentcalc') {
2315: &get_student_rowlabels($sheet);
2316: } else {
2317: &get_assess_rowlabels($sheet);
1.35 www 2318: }
1.136 matthew 2319: # Determine if any of the information has changed
1.119 matthew 2320: my %f=&getformulas($sheet);
1.104 matthew 2321: my $changed=0;
2322:
1.119 matthew 2323: $sheet->{'maxrow'} = 0;
1.104 matthew 2324: my %existing=();
2325: # Now obsolete rows
1.147 matthew 2326: foreach my $cell (keys(%f)) {
2327: my $formula = $f{$cell};
1.136 matthew 2328: next if ($cell !~ /^A(\d+)/);
2329: $sheet->{'maxrow'} = $1 if ($1 > $sheet->{'maxrow'});
2330: my ($usy,$ufn)=split(/__&&&\__/,$formula);
1.104 matthew 2331: $existing{$usy}=1;
1.119 matthew 2332: unless ((exists($sheet->{'rowlabel'}->{$usy}) &&
2333: (defined($sheet->{'rowlabel'}->{$usy})) || (!$1) ||
1.136 matthew 2334: ($formula =~ /^(~~~|---)/) )) {
1.104 matthew 2335: $f{$_}='!!! Obsolete';
2336: $changed=1;
2337: } elsif ($ufn) {
1.136 matthew 2338: # I do not think this works any more
1.119 matthew 2339: $sheet->{'rowlabel'}->{$usy}
1.136 matthew 2340: =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn&\usymb\=/;
1.104 matthew 2341: }
1.35 www 2342: }
1.104 matthew 2343: # New and unknown keys
1.119 matthew 2344: foreach (keys(%{$sheet->{'rowlabel'}})) {
1.104 matthew 2345: unless ($existing{$_}) {
2346: $changed=1;
1.119 matthew 2347: $sheet->{'maxrow'}++;
2348: $f{'A'.$sheet->{'maxrow'}}=$_;
1.78 matthew 2349: }
1.104 matthew 2350: }
1.119 matthew 2351: if ($changed) {
1.124 matthew 2352: $sheet->{'f'} = \%f;
2353: &setformulas($sheet);
1.119 matthew 2354: }
1.5 www 2355: }
1.3 www 2356:
1.24 www 2357: # ------------------------------------------------ Load data for one assessment
1.16 www 2358:
1.135 matthew 2359: sub loadstudent{
1.140 matthew 2360: my ($sheet,$r,$c)=@_;
2361: my %constants=();
2362: my %formulas=&getformulas($sheet);
1.119 matthew 2363: $cachedassess=$sheet->{'uname'}.':'.$sheet->{'udom'};
1.102 matthew 2364: # Get ALL the student preformance data
1.119 matthew 2365: my @tmp = &Apache::lonnet::dump($sheet->{'cid'},
2366: $sheet->{'udom'},
2367: $sheet->{'uname'},
1.102 matthew 2368: undef);
2369: if ($tmp[0] !~ /^error:/) {
2370: %cachedstores = @tmp;
1.39 www 2371: }
1.102 matthew 2372: undef @tmp;
2373: #
1.36 www 2374: my @assessdata=();
1.145 matthew 2375: foreach my $cell (keys(%formulas)) {
2376: my $value = $formulas{$cell};
1.140 matthew 2377: if(defined($c) && ($c->aborted())) {
2378: last;
2379: }
1.136 matthew 2380: next if ($cell !~ /^A(\d+)/);
1.104 matthew 2381: my $row=$1;
1.136 matthew 2382: next if (($value =~ /^[!~-]/) || ($row==0));
2383: my ($usy,$ufn)=split(/__&&&\__/,$value);
1.128 matthew 2384: @assessdata=&exportsheet($sheet,$sheet->{'uname'},
1.119 matthew 2385: $sheet->{'udom'},
1.140 matthew 2386: 'assesscalc',$usy,$ufn,$r);
1.104 matthew 2387: my $index=0;
1.145 matthew 2388: foreach my $col ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2389: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.136 matthew 2390: if (defined($assessdata[$index])) {
1.104 matthew 2391: if ($assessdata[$index]=~/\D/) {
1.140 matthew 2392: $constants{$col.$row}="'".$assessdata[$index]."'";
1.104 matthew 2393: } else {
1.140 matthew 2394: $constants{$col.$row}=$assessdata[$index];
1.104 matthew 2395: }
1.145 matthew 2396: $formulas{$col.$row}='import' if ($col ne 'A');
1.104 matthew 2397: }
2398: $index++;
1.16 www 2399: }
1.78 matthew 2400: }
1.39 www 2401: $cachedassess='';
2402: undef %cachedstores;
1.140 matthew 2403: $sheet->{'f'} = \%formulas;
1.124 matthew 2404: &setformulas($sheet);
1.140 matthew 2405: &setconstants($sheet,\%constants);
1.16 www 2406: }
2407:
1.24 www 2408: # --------------------------------------------------- Load data for one student
1.109 matthew 2409: #
1.30 www 2410: sub loadcourse {
1.140 matthew 2411: my ($sheet,$r,$c)=@_;
1.135 matthew 2412: #
1.140 matthew 2413: my %constants=();
2414: my %formulas=&getformulas($sheet);
1.135 matthew 2415: #
1.37 www 2416: my $total=0;
1.140 matthew 2417: foreach (keys(%formulas)) {
1.37 www 2418: if ($_=~/^A(\d+)/) {
1.140 matthew 2419: unless ($formulas{$_}=~/^[\!\~\-]/) { $total++; }
1.37 www 2420: }
1.78 matthew 2421: }
1.37 www 2422: my $now=0;
2423: my $since=time;
1.39 www 2424: $r->print(<<ENDPOP);
2425: <script>
2426: popwin=open('','popwin','width=400,height=100');
2427: popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
1.50 www 2428: '<h3>Spreadsheet Calculation Progress</h3>'+
1.39 www 2429: '<form name=popremain>'+
2430: '<input type=text size=35 name=remaining value=Starting></form>'+
2431: '</body></html>');
1.42 www 2432: popwin.document.close();
1.39 www 2433: </script>
2434: ENDPOP
1.37 www 2435: $r->rflush();
1.140 matthew 2436: foreach (keys(%formulas)) {
2437: if(defined($c) && ($c->aborted())) {
2438: last;
2439: }
1.104 matthew 2440: next if ($_!~/^A(\d+)/);
2441: my $row=$1;
1.140 matthew 2442: next if (($formulas{$_}=~/^[\!\~\-]/) || ($row==0));
2443: my ($sname,$sdom) = split(':',$formulas{$_});
2444: my @studentdata=&exportsheet($sheet,$sname,$sdom,'studentcalc',
2445: undef,undef,$r);
1.104 matthew 2446: undef %userrdatas;
2447: $now++;
2448: $r->print('<script>popwin.document.popremain.remaining.value="'.
1.37 www 2449: $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
1.104 matthew 2450: ' secs remaining";</script>');
2451: $r->rflush();
2452: #
2453: my $index=0;
2454: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2455: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.132 matthew 2456: if (defined($studentdata[$index])) {
1.104 matthew 2457: my $col=$_;
2458: if ($studentdata[$index]=~/\D/) {
1.140 matthew 2459: $constants{$col.$row}="'".$studentdata[$index]."'";
1.104 matthew 2460: } else {
1.140 matthew 2461: $constants{$col.$row}=$studentdata[$index];
1.104 matthew 2462: }
2463: unless ($col eq 'A') {
1.140 matthew 2464: $formulas{$col.$row}='import';
1.104 matthew 2465: }
1.132 matthew 2466: }
2467: $index++;
1.24 www 2468: }
1.78 matthew 2469: }
1.140 matthew 2470: $sheet->{'f'}=\%formulas;
1.124 matthew 2471: &setformulas($sheet);
1.140 matthew 2472: &setconstants($sheet,\%constants);
1.43 www 2473: $r->print('<script>popwin.close()</script>');
1.37 www 2474: $r->rflush();
1.24 www 2475: }
2476:
1.6 www 2477: # ------------------------------------------------ Load data for one assessment
1.109 matthew 2478: #
1.29 www 2479: sub loadassessment {
1.140 matthew 2480: my ($sheet,$r,$c)=@_;
1.29 www 2481:
1.119 matthew 2482: my $uhome = $sheet->{'uhome'};
2483: my $uname = $sheet->{'uname'};
2484: my $udom = $sheet->{'udom'};
2485: my $symb = $sheet->{'usymb'};
2486: my $cid = $sheet->{'cid'};
2487: my $cnum = $sheet->{'cnum'};
2488: my $cdom = $sheet->{'cdom'};
2489: my $chome = $sheet->{'chome'};
1.29 www 2490:
1.6 www 2491: my $namespace;
1.29 www 2492: unless ($namespace=$cid) { return ''; }
1.104 matthew 2493: # Get stored values
2494: my %returnhash=();
2495: if ($cachedassess eq $uname.':'.$udom) {
2496: #
2497: # get data out of the dumped stores
2498: #
2499: my $version=$cachedstores{'version:'.$symb};
2500: my $scope;
2501: for ($scope=1;$scope<=$version;$scope++) {
2502: foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
2503: $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
2504: }
2505: }
2506: } else {
2507: #
2508: # restore individual
2509: #
1.109 matthew 2510: %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
2511: for (my $version=1;$version<=$returnhash{'version'};$version++) {
1.104 matthew 2512: foreach (split(/\:/,$returnhash{$version.':keys'})) {
2513: $returnhash{$_}=$returnhash{$version.':'.$_};
2514: }
2515: }
1.6 www 2516: }
1.109 matthew 2517: #
1.104 matthew 2518: # returnhash now has all stores for this resource
2519: # convert all "_" to "." to be able to use libraries, multiparts, etc
1.109 matthew 2520: #
2521: # This is dumb. It is also necessary :(
1.76 www 2522: my @oldkeys=keys %returnhash;
1.109 matthew 2523: #
1.116 matthew 2524: foreach my $name (@oldkeys) {
2525: my $value=$returnhash{$name};
2526: delete $returnhash{$name};
1.76 www 2527: $name=~s/\_/\./g;
2528: $returnhash{$name}=$value;
1.78 matthew 2529: }
1.104 matthew 2530: # initialize coursedata and userdata for this user
1.31 www 2531: undef %courseopt;
2532: undef %useropt;
1.29 www 2533:
2534: my $userprefix=$uname.'_'.$udom.'_';
1.116 matthew 2535:
1.11 www 2536: unless ($uhome eq 'no_host') {
1.104 matthew 2537: # Get coursedata
1.105 matthew 2538: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
1.116 matthew 2539: my %Tmp = &Apache::lonnet::dump('resourcedata',$cdom,$cnum);
2540: $courserdatas{$cid}=\%Tmp;
2541: $courserdatas{$cid.'.last_cache'}=time;
1.105 matthew 2542: }
1.116 matthew 2543: while (my ($name,$value) = each(%{$courserdatas{$cid}})) {
2544: $courseopt{$userprefix.$name}=$value;
1.104 matthew 2545: }
2546: # Get userdata (if present)
1.116 matthew 2547: unless ((time-$userrdatas{$uname.'@'.$udom.'.last_cache'})<240) {
2548: my %Tmp = &Apache::lonnet::dump('resourcedata',$udom,$uname);
2549: $userrdatas{$cid} = \%Tmp;
1.114 matthew 2550: # Most of the time the user does not have a 'resourcedata.db'
2551: # file. We need to cache that we got nothing instead of bothering
2552: # with requesting it every time.
1.116 matthew 2553: $userrdatas{$uname.'@'.$udom.'.last_cache'}=time;
1.109 matthew 2554: }
1.116 matthew 2555: while (my ($name,$value) = each(%{$userrdatas{$cid}})) {
2556: $useropt{$userprefix.$name}=$value;
1.104 matthew 2557: }
1.29 www 2558: }
1.104 matthew 2559: # now courseopt, useropt initialized for this user and course
2560: # (used by parmval)
2561: #
2562: # Load keys for this assessment only
2563: #
1.60 www 2564: my %thisassess=();
2565: my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
1.78 matthew 2566: foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
1.60 www 2567: $thisassess{$_}=1;
1.78 matthew 2568: }
1.104 matthew 2569: #
2570: # Load parameters
2571: #
2572: my %c=();
2573: if (tie(%parmhash,'GDBM_File',
1.119 matthew 2574: $sheet->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
2575: my %f=&getformulas($sheet);
1.125 matthew 2576: foreach my $cell (keys(%f)) {
2577: next if ($cell !~ /^A/);
2578: next if ($f{$cell} =~/^[\!\~\-]/);
2579: if ($f{$cell}=~/^parameter/) {
2580: if (defined($thisassess{$f{$cell}})) {
2581: my $val = &parmval($f{$cell},$sheet);
2582: $c{$cell} = $val;
2583: $c{$f{$cell}} = $val;
1.104 matthew 2584: }
2585: } else {
1.125 matthew 2586: my $key=$f{$cell};
1.104 matthew 2587: my $ckey=$key;
2588: $key=~s/^stores\_/resource\./;
2589: $key=~s/\_/\./g;
1.125 matthew 2590: $c{$cell}=$returnhash{$key};
1.104 matthew 2591: $c{$ckey}=$returnhash{$key};
2592: }
1.6 www 2593: }
1.104 matthew 2594: untie(%parmhash);
1.78 matthew 2595: }
1.122 matthew 2596: &setconstants($sheet,\%c);
1.6 www 2597: }
2598:
1.10 www 2599: # --------------------------------------------------------- Various form fields
2600:
2601: sub textfield {
2602: my ($title,$name,$value)=@_;
2603: return "\n<p><b>$title:</b><br>".
1.104 matthew 2604: '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
1.10 www 2605: }
2606:
2607: sub hiddenfield {
2608: my ($name,$value)=@_;
2609: return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
2610: }
2611:
2612: sub selectbox {
2613: my ($title,$name,$value,%options)=@_;
2614: my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
1.78 matthew 2615: foreach (sort keys(%options)) {
1.10 www 2616: $selout.='<option value="'.$_.'"';
2617: if ($_ eq $value) { $selout.=' selected'; }
2618: $selout.='>'.$options{$_}.'</option>';
1.78 matthew 2619: }
1.10 www 2620: return $selout.'</select>';
2621: }
2622:
1.28 www 2623: # =============================================== Update information in a sheet
2624: #
2625: # Add new users or assessments, etc.
2626: #
2627:
2628: sub updatesheet {
1.119 matthew 2629: my ($sheet)=@_;
1.136 matthew 2630: if ($sheet->{'sheettype'} eq 'classcalc') {
1.119 matthew 2631: return &updateclasssheet($sheet);
1.28 www 2632: } else {
1.119 matthew 2633: return &updatestudentassesssheet($sheet);
1.28 www 2634: }
2635: }
2636:
2637: # =================================================== Load the rows for a sheet
2638: #
2639: # Import the data for rows
2640: #
2641:
1.37 www 2642: sub loadrows {
1.119 matthew 2643: my ($sheet,$r)=@_;
1.140 matthew 2644: my $c = $r->connection;
1.119 matthew 2645: my $stype=$sheet->{'sheettype'};
1.28 www 2646: if ($stype eq 'classcalc') {
1.140 matthew 2647: &loadcourse($sheet,$r,$c);
1.28 www 2648: } elsif ($stype eq 'studentcalc') {
1.140 matthew 2649: &loadstudent($sheet,$r,$c);
1.28 www 2650: } else {
1.140 matthew 2651: &loadassessment($sheet,$r,$c);
1.28 www 2652: }
2653: }
2654:
1.47 www 2655: # ======================================================= Forced recalculation?
2656:
2657: sub checkthis {
2658: my ($keyname,$time)=@_;
1.144 matthew 2659: if (! exists($expiredates{$keyname})) {
2660: return 0;
2661: } else {
2662: return ($time<$expiredates{$keyname});
2663: }
1.47 www 2664: }
1.104 matthew 2665:
1.47 www 2666: sub forcedrecalc {
2667: my ($uname,$udom,$stype,$usymb)=@_;
2668: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2669: my $time=$oldsheets{$key.'.time'};
1.53 www 2670: if ($ENV{'form.forcerecalc'}) { return 1; }
1.47 www 2671: unless ($time) { return 1; }
2672: if ($stype eq 'assesscalc') {
1.120 matthew 2673: my $map=(split(/___/,$usymb))[0];
1.47 www 2674: if (&checkthis('::assesscalc:',$time) ||
2675: &checkthis('::assesscalc:'.$map,$time) ||
2676: &checkthis('::assesscalc:'.$usymb,$time) ||
1.49 www 2677: &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
2678: &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
2679: &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
1.47 www 2680: return 1;
2681: }
2682: } else {
2683: if (&checkthis('::studentcalc:',$time) ||
1.51 www 2684: &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
1.47 www 2685: return 1;
2686: }
2687: }
2688: return 0;
2689: }
2690:
1.28 www 2691: # ============================================================== Export handler
1.128 matthew 2692: # exportsheet
2693: # returns the export row for a spreadsheet.
2694: #
1.28 www 2695: sub exportsheet {
1.140 matthew 2696: my ($sheet,$uname,$udom,$stype,$usymb,$fn,$r)=@_;
1.145 matthew 2697: my $flag = 0;
1.128 matthew 2698: $uname = $uname || $sheet->{'uname'};
2699: $udom = $udom || $sheet->{'udom'};
2700: $stype = $stype || $sheet->{'sheettype'};
1.104 matthew 2701: my @exportarr=();
1.132 matthew 2702: if (defined($usymb) && ($usymb=~/^\_(\w+)/) &&
2703: (!defined($fn) || $fn eq '')) {
1.104 matthew 2704: $fn='default_'.$1;
2705: }
2706: #
2707: # Check if cached
2708: #
2709: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2710: my $found='';
2711: if ($oldsheets{$key}) {
1.120 matthew 2712: foreach (split(/___&\___/,$oldsheets{$key})) {
2713: my ($name,$value)=split(/___=___/,$_);
1.46 www 2714: if ($name eq $fn) {
1.104 matthew 2715: $found=$value;
1.46 www 2716: }
1.104 matthew 2717: }
1.46 www 2718: }
1.104 matthew 2719: unless ($found) {
1.128 matthew 2720: &cachedssheets($sheet,$uname,$udom);
1.104 matthew 2721: if ($oldsheets{$key}) {
1.120 matthew 2722: foreach (split(/___&\___/,$oldsheets{$key})) {
2723: my ($name,$value)=split(/___=___/,$_);
1.104 matthew 2724: if ($name eq $fn) {
2725: $found=$value;
2726: }
2727: }
2728: }
1.44 www 2729: }
1.104 matthew 2730: #
2731: # Check if still valid
2732: #
2733: if ($found) {
2734: if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
2735: $found='';
2736: }
2737: }
2738: if ($found) {
2739: #
2740: # Return what was cached
2741: #
1.120 matthew 2742: @exportarr=split(/___;___/,$found);
2743: return @exportarr;
2744: }
2745: #
2746: # Not cached
1.135 matthew 2747: #
1.128 matthew 2748: my ($newsheet)=&makenewsheet($uname,$udom,$stype,$usymb);
2749: &readsheet($newsheet,$fn);
2750: &updatesheet($newsheet);
1.140 matthew 2751: &loadrows($newsheet,$r);
1.128 matthew 2752: &calcsheet($newsheet);
2753: @exportarr=&exportdata($newsheet);
1.131 matthew 2754: ##
2755: ## Store now
2756: ##
1.120 matthew 2757: #
1.131 matthew 2758: # load in the old value
1.120 matthew 2759: #
1.131 matthew 2760: my %currentlystored=();
1.120 matthew 2761: if ($stype eq 'studentcalc') {
1.131 matthew 2762: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets',
2763: [$key],
2764: $sheet->{'cdom'},$sheet->{'cnum'});
2765: if ($tmp[0]!~/^error/) {
1.145 matthew 2766: # We only got one key, so we will access it directly.
2767: foreach (split('___&___',$tmp[1])) {
2768: my ($key,$value) = split('___=___',$_);
2769: $key = '' if (! defined($key));
2770: $currentlystored{$key} = $value;
2771: }
1.131 matthew 2772: }
2773: } else {
2774: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets_'.
2775: $sheet->{'cid'},[$key],
2776: $sheet->{'udom'},$sheet->{'uname'});
2777: if ($tmp[0]!~/^error/) {
1.145 matthew 2778: # We only got one key, so we will access it directly.
2779: foreach (split('___&___',$tmp[1])) {
2780: my ($key,$value) = split('___=___',$_);
2781: $key = '' if (! defined($key));
2782: $currentlystored{$key} = $value;
2783: }
1.120 matthew 2784: }
2785: }
1.131 matthew 2786: #
2787: # Add the new line
2788: #
1.120 matthew 2789: $currentlystored{$fn}=join('___;___',@exportarr);
2790: #
1.131 matthew 2791: # Stick everything back together
2792: #
1.120 matthew 2793: my $newstore='';
2794: foreach (keys(%currentlystored)) {
2795: if ($newstore) { $newstore.='___&___'; }
2796: $newstore.=$_.'___=___'.$currentlystored{$_};
2797: }
2798: my $now=time;
1.131 matthew 2799: #
2800: # Store away the new value
2801: #
1.144 matthew 2802: my $timekey = $key.'.time';
1.120 matthew 2803: if ($stype eq 'studentcalc') {
1.144 matthew 2804: my $result = &Apache::lonnet::put('nohist_calculatedsheets',
2805: { $key => $newstore,
2806: $timekey => $now },
2807: $sheet->{'cdom'},
2808: $sheet->{'cnum'});
2809: } else {
2810: my $result = &Apache::lonnet::put('nohist_calculatedsheets_'.$sheet->{'cid'},
2811: { $key => $newstore,
2812: $timekey => $now },
2813: $sheet->{'udom'},
2814: $sheet->{'uname'});
1.78 matthew 2815: }
1.104 matthew 2816: return @exportarr;
1.44 www 2817: }
1.104 matthew 2818:
1.48 www 2819: # ============================================================ Expiration Dates
2820: #
2821: # Load previously cached student spreadsheets for this course
2822: #
1.136 matthew 2823: sub load_spreadsheet_expirationdates {
1.48 www 2824: undef %expiredates;
2825: my $cid=$ENV{'request.course.id'};
1.128 matthew 2826: my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
2827: $ENV{'course.'.$cid.'.domain'},
2828: $ENV{'course.'.$cid.'.num'});
1.140 matthew 2829: if (lc($tmp[0]) !~ /^error/){
1.128 matthew 2830: %expiredates = @tmp;
1.48 www 2831: }
2832: }
1.44 www 2833:
2834: # ===================================================== Calculated sheets cache
2835: #
1.46 www 2836: # Load previously cached student spreadsheets for this course
1.44 www 2837: #
2838:
1.46 www 2839: sub cachedcsheets {
1.44 www 2840: my $cid=$ENV{'request.course.id'};
1.128 matthew 2841: my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
2842: $ENV{'course.'.$cid.'.domain'},
2843: $ENV{'course.'.$cid.'.num'});
2844: if ($tmp[0] !~ /^error/) {
2845: my %StupidTempHash = @tmp;
2846: while (my ($key,$value) = each %StupidTempHash) {
2847: $oldsheets{$key} = $value;
1.78 matthew 2848: }
1.44 www 2849: }
1.28 www 2850: }
2851:
1.46 www 2852: # ===================================================== Calculated sheets cache
2853: #
2854: # Load previously cached assessment spreadsheets for this student
2855: #
2856:
2857: sub cachedssheets {
1.128 matthew 2858: my ($sheet,$uname,$udom) = @_;
2859: $uname = $uname || $sheet->{'uname'};
2860: $udom = $udom || $sheet->{'udom'};
1.136 matthew 2861: if (! $loadedcaches{$uname.'_'.$udom}) {
1.128 matthew 2862: my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
2863: $sheet->{'udom'},
2864: $sheet->{'uname'});
2865: if ($tmp[0] !~ /^error/) {
1.136 matthew 2866: my %TempHash = @tmp;
2867: my $count = 0;
2868: while (my ($key,$value) = each %TempHash) {
1.128 matthew 2869: $oldsheets{$key} = $value;
1.136 matthew 2870: $count++;
1.128 matthew 2871: }
2872: $loadedcaches{$sheet->{'uname'}.'_'.$sheet->{'udom'}}=1;
1.78 matthew 2873: }
1.46 www 2874: }
1.136 matthew 2875:
1.46 www 2876: }
2877:
2878: # ===================================================== Calculated sheets cache
2879: #
2880: # Load previously cached assessment spreadsheets for this student
2881: #
2882:
1.12 www 2883: # ================================================================ Main handler
1.28 www 2884: #
2885: # Interactive call to screen
2886: #
2887: #
1.3 www 2888: sub handler {
1.7 www 2889: my $r=shift;
1.110 www 2890:
1.135 matthew 2891: my ($sheettype) = ($r->uri=~/\/(\w+)$/);
2892:
1.118 matthew 2893: if (! exists($ENV{'form.Status'})) {
2894: $ENV{'form.Status'} = 'Active';
2895: }
1.135 matthew 2896: if ( ! exists($ENV{'form.output'}) ||
2897: ($sheettype ne 'classcalc' &&
2898: lc($ENV{'form.output'}) eq 'recursive excel')) {
1.134 matthew 2899: $ENV{'form.output'} = 'HTML';
2900: }
1.136 matthew 2901: #
2902: # Overload checking
2903: #
1.116 matthew 2904: # Check this server
1.111 matthew 2905: my $loaderror=&Apache::lonnet::overloaderror($r);
2906: if ($loaderror) { return $loaderror; }
1.116 matthew 2907: # Check the course homeserver
1.111 matthew 2908: $loaderror= &Apache::lonnet::overloaderror($r,
2909: $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
2910: if ($loaderror) { return $loaderror; }
1.136 matthew 2911: #
2912: # HTML Header
2913: #
1.28 www 2914: if ($r->header_only) {
1.104 matthew 2915: $r->content_type('text/html');
2916: $r->send_http_header;
2917: return OK;
2918: }
1.136 matthew 2919: #
1.104 matthew 2920: # Global directory configs
1.136 matthew 2921: #
1.106 matthew 2922: $includedir = $r->dir_config('lonIncludes');
2923: $tmpdir = $r->dir_config('lonDaemons').'/tmp/';
1.136 matthew 2924: #
2925: # Roles Checking
2926: #
1.104 matthew 2927: # Needs to be in a course
1.106 matthew 2928: if (! $ENV{'request.course.fn'}) {
2929: # Not in a course, or not allowed to modify parms
2930: $ENV{'user.error.msg'}=
2931: $r->uri.":opa:0:0:Cannot modify spreadsheet";
2932: return HTTP_NOT_ACCEPTABLE;
2933: }
1.136 matthew 2934: #
1.106 matthew 2935: # Get query string for limited number of parameters
1.136 matthew 2936: #
1.139 matthew 2937: &Apache::loncommon::get_unprocessed_cgi
2938: ($ENV{'QUERY_STRING'},['uname','udom','usymb','ufn','mapid','resid']);
1.136 matthew 2939: #
2940: # Deal with restricted student permissions
2941: #
1.111 matthew 2942: if ($ENV{'request.role'} =~ /^st\./) {
2943: delete $ENV{'form.unewfield'} if (exists($ENV{'form.unewfield'}));
2944: delete $ENV{'form.unewformula'} if (exists($ENV{'form.unewformula'}));
2945: }
1.136 matthew 2946: #
2947: # Clean up symb and spreadsheet filename
2948: #
1.106 matthew 2949: if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
2950: $ENV{'form.ufn'}='default_'.$1;
2951: }
1.136 matthew 2952: #
1.106 matthew 2953: # Interactive loading of specific sheet?
1.136 matthew 2954: #
1.106 matthew 2955: if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
2956: $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
2957: }
2958: #
2959: # Determine the user name and domain for the sheet.
2960: my $aname;
2961: my $adom;
2962: unless ($ENV{'form.uname'}) {
2963: $aname=$ENV{'user.name'};
2964: $adom=$ENV{'user.domain'};
2965: } else {
2966: $aname=$ENV{'form.uname'};
2967: $adom=$ENV{'form.udom'};
2968: }
2969: #
1.136 matthew 2970: # Open page, try to prevent browser cache.
2971: #
1.106 matthew 2972: $r->content_type('text/html');
2973: $r->header_out('Cache-control','no-cache');
2974: $r->header_out('Pragma','no-cache');
2975: $r->send_http_header;
1.136 matthew 2976: #
2977: # Header....
2978: #
1.106 matthew 2979: $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
1.138 matthew 2980: my $nothing = "''";
2981: if ($ENV{'browser.type'} eq 'explorer') {
2982: $nothing = "'javascript:void(0);'";
2983: }
2984:
1.111 matthew 2985: if ($ENV{'request.role'} !~ /^st\./) {
2986: $r->print(<<ENDSCRIPT);
1.10 www 2987: <script language="JavaScript">
2988:
1.138 matthew 2989: var editwin;
2990:
2991: function celledit(cellname,cellformula) {
2992: var edit_text = '';
1.151 ! matthew 2993: // cellformula may contain less-than and greater-than symbols, so
! 2994: // we need to escape them?
1.138 matthew 2995: edit_text +='<html><head><title>Cell Edit Window</title></head><body>';
2996: edit_text += '<form name="editwinform">';
2997: edit_text += '<center><h3>Cell '+cellname+'</h3>';
2998: edit_text += '<textarea name="newformula" cols="40" rows="6"';
2999: edit_text += ' wrap="off" >'+cellformula+'</textarea>';
3000: edit_text += '</br>';
3001: edit_text += '<input type="button" name="accept" value="Accept"';
3002: edit_text += ' onClick=\\\'javascript:';
3003: edit_text += 'opener.document.sheet.unewfield.value=';
3004: edit_text += '"'+cellname+'";';
3005: edit_text += 'opener.document.sheet.unewformula.value=';
3006: edit_text += 'document.editwinform.newformula.value;';
3007: edit_text += 'opener.document.sheet.submit();';
3008: edit_text += 'self.close()\\\' />';
3009: edit_text += ' ';
3010: edit_text += '<input type="button" name="abort" ';
3011: edit_text += 'value="Discard Changes"';
3012: edit_text += ' onClick="javascript:self.close()" />';
3013: edit_text += '</center></body></html>';
3014:
3015: if (editwin != null && !(editwin.closed) ) {
3016: editwin.close();
1.10 www 3017: }
1.138 matthew 3018:
3019: editwin = window.open($nothing,'CellEditWin','height=200,width=350,scrollbars=no,resizeable=yes,alwaysRaised=yes,dependent=yes',true);
3020: editwin.document.write(edit_text);
1.10 www 3021: }
3022:
1.55 www 3023: function changesheet(cn) {
3024: document.sheet.unewfield.value=cn;
3025: document.sheet.unewformula.value='changesheet';
3026: document.sheet.submit();
3027: }
3028:
1.92 www 3029: function insertrow(cn) {
3030: document.sheet.unewfield.value='insertrow';
3031: document.sheet.unewformula.value=cn;
3032: document.sheet.submit();
3033: }
3034:
1.10 www 3035: </script>
3036: ENDSCRIPT
1.111 matthew 3037: }
1.106 matthew 3038: $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
1.138 matthew 3039: '<form action="'.$r->uri.'" name="sheet" method="post">');
1.106 matthew 3040: $r->print(&hiddenfield('uname',$ENV{'form.uname'}).
3041: &hiddenfield('udom',$ENV{'form.udom'}).
3042: &hiddenfield('usymb',$ENV{'form.usymb'}).
3043: &hiddenfield('unewfield','').
3044: &hiddenfield('unewformula',''));
3045: $r->rflush();
3046: #
3047: # Full recalc?
1.136 matthew 3048: #
1.106 matthew 3049: if ($ENV{'form.forcerecalc'}) {
3050: $r->print('<h4>Completely Recalculating Sheet ...</h4>');
3051: undef %spreadsheets;
3052: undef %courserdatas;
3053: undef %userrdatas;
3054: undef %defaultsheets;
1.136 matthew 3055: undef %rowlabel_cache;
1.106 matthew 3056: }
3057: # Read new sheet or modified worksheet
1.135 matthew 3058: my ($sheet)=&makenewsheet($aname,$adom,$sheettype,$ENV{'form.usymb'});
1.106 matthew 3059: #
1.139 matthew 3060: # Check user permissions
3061: if (($sheet->{'sheettype'} eq 'classcalc' ) ||
3062: ($sheet->{'uname'} ne $ENV{'user.name'} ) ||
3063: ($sheet->{'udom'} ne $ENV{'user.domain'})) {
3064: unless (&Apache::lonnet::allowed('vgr',$sheet->{'cid'})) {
3065: $r->print('<h1>Access Permission Denied</h1>'.
3066: '</form></body></html>');
3067: return OK;
3068: }
3069: }
3070: # Print out user information
3071: $r->print('<h2>'.$sheet->{'coursedesc'}.'</h2>');
3072: if ($sheet->{'sheettype'} ne 'classcalc') {
3073: $r->print('<h2>'.&gettitle($sheet).'</h2><p>');
3074: }
3075: if ($sheet->{'sheettype'} eq 'assesscalc') {
3076: $r->print('<b>User:</b> '.$sheet->{'uname'}.
3077: '<br /><b>Domain:</b> '.$sheet->{'udom'}.'<br />');
3078: }
3079: if ($sheet->{'sheettype'} eq 'studentcalc' ||
3080: $sheet->{'sheettype'} eq 'assesscalc') {
3081: $r->print('<b>Section/Group:</b>'.$sheet->{'csec'}.'</p>');
3082: }
3083: #
1.106 matthew 3084: # If a new formula had been entered, go from work copy
3085: if ($ENV{'form.unewfield'}) {
3086: $r->print('<h2>Modified Workcopy</h2>');
3087: $ENV{'form.unewformula'}=~s/\'/\"/g;
3088: $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
3089: $ENV{'form.unewformula'}.'<p>');
1.119 matthew 3090: $sheet->{'filename'} = $ENV{'form.ufn'};
3091: &tmpread($sheet,$ENV{'form.unewfield'},$ENV{'form.unewformula'});
1.106 matthew 3092: } elsif ($ENV{'form.saveas'}) {
1.119 matthew 3093: $sheet->{'filename'} = $ENV{'form.ufn'};
3094: &tmpread($sheet);
1.106 matthew 3095: } else {
1.119 matthew 3096: &readsheet($sheet,$ENV{'form.ufn'});
1.106 matthew 3097: }
3098: # Additional options
1.119 matthew 3099: if ($sheet->{'sheettype'} eq 'assesscalc') {
1.106 matthew 3100: $r->print('<p><font size=+2>'.
3101: '<a href="/adm/studentcalc?'.
1.119 matthew 3102: 'uname='.$sheet->{'uname'}.
3103: '&udom='.$sheet->{'udom'}.'">'.
1.139 matthew 3104: 'Level up: Student Sheet</a></font></p>');
1.106 matthew 3105: }
1.119 matthew 3106: if (($sheet->{'sheettype'} eq 'studentcalc') &&
3107: (&Apache::lonnet::allowed('vgr',$sheet->{'cid'}))) {
1.106 matthew 3108: $r->print ('<p><font size=+2><a href="/adm/classcalc">'.
1.139 matthew 3109: 'Level up: Course Sheet</a></font></p>');
1.106 matthew 3110: }
1.139 matthew 3111: # Recalc button
3112: $r->print('<br />'.
3113: '<input type="submit" name="forcerecalc" '.
3114: 'value="Completely Recalculate Sheet"></p>');
1.106 matthew 3115: # Save dialog
3116: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3117: my $fname=$ENV{'form.ufn'};
3118: $fname=~s/\_[^\_]+$//;
3119: if ($fname eq 'default') { $fname='course_default'; }
3120: $r->print('<input type=submit name=saveas value="Save as ...">'.
3121: '<input type=text size=20 name=newfn value="'.$fname.'">'.
3122: 'make default: <input type=checkbox name="makedefufn"><p>');
3123: }
1.119 matthew 3124: $r->print(&hiddenfield('ufn',$sheet->{'filename'}));
1.106 matthew 3125: # Load dialog
3126: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3127: $r->print('<p><input type=submit name=load value="Load ...">'.
3128: '<select name="loadthissheet">'.
3129: '<option name="default">Default</option>');
1.119 matthew 3130: foreach (&othersheets($sheet)) {
1.106 matthew 3131: $r->print('<option name="'.$_.'"');
3132: if ($ENV{'form.ufn'} eq $_) {
3133: $r->print(' selected');
1.104 matthew 3134: }
1.106 matthew 3135: $r->print('>'.$_.'</option>');
3136: }
3137: $r->print('</select><p>');
1.119 matthew 3138: if ($sheet->{'sheettype'} eq 'studentcalc') {
1.116 matthew 3139: &setothersheets($sheet,
1.119 matthew 3140: &othersheets($sheet,'assesscalc'));
1.104 matthew 3141: }
1.106 matthew 3142: }
1.136 matthew 3143: #
3144: # Set up caching mechanisms
3145: #
3146: &load_spreadsheet_expirationdates();
3147: # Clear out old caches if we have not seen this class before.
3148: if (exists($oldsheets{'course'}) &&
3149: $oldsheets{'course'} ne $sheet->{'cid'}) {
3150: undef %oldsheets;
3151: undef %loadedcaches;
3152: }
3153: $oldsheets{'course'} = $sheet->{'cid'};
3154: #
1.119 matthew 3155: if ($sheet->{'sheettype'} eq 'classcalc') {
1.106 matthew 3156: $r->print("Loading previously calculated student sheets ...\n");
1.104 matthew 3157: $r->rflush();
1.106 matthew 3158: &cachedcsheets();
1.119 matthew 3159: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.106 matthew 3160: $r->print("Loading previously calculated assessment sheets ...\n");
1.46 www 3161: $r->rflush();
1.128 matthew 3162: &cachedssheets($sheet);
1.106 matthew 3163: }
3164: # Update sheet, load rows
3165: $r->print("Loaded sheet(s), updating rows ...<br>\n");
3166: $r->rflush();
3167: #
1.119 matthew 3168: &updatesheet($sheet);
1.106 matthew 3169: $r->print("Updated rows, loading row data ...\n");
3170: $r->rflush();
3171: #
1.119 matthew 3172: &loadrows($sheet,$r);
1.106 matthew 3173: $r->print("Loaded row data, calculating sheet ...<br>\n");
3174: $r->rflush();
3175: #
1.116 matthew 3176: my $calcoutput=&calcsheet($sheet);
1.106 matthew 3177: $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
3178: # See if something to save
3179: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3180: my $fname='';
3181: if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
3182: $fname=~s/\W/\_/g;
3183: if ($fname eq 'default') { $fname='course_default'; }
1.119 matthew 3184: $fname.='_'.$sheet->{'sheettype'};
3185: $sheet->{'filename'} = $fname;
1.106 matthew 3186: $ENV{'form.ufn'}=$fname;
3187: $r->print('<p>Saving spreadsheet: '.
1.119 matthew 3188: &writesheet($sheet,$ENV{'form.makedefufn'}).
1.116 matthew 3189: '<p>');
1.104 matthew 3190: }
1.106 matthew 3191: }
3192: #
1.116 matthew 3193: # Write the modified worksheet
1.139 matthew 3194: $r->print('<b>Current sheet:</b> '.$sheet->{'filename'}.'</p>');
1.119 matthew 3195: &tmpwrite($sheet);
1.141 matthew 3196: if ($sheet->{'sheettype'} eq 'assesscalc') {
1.139 matthew 3197: $r->print('<p>Show rows with empty A column: ');
1.62 www 3198: } else {
1.140 matthew 3199: $r->print('<p>Show empty rows: ');
1.120 matthew 3200: }
1.106 matthew 3201: #
1.77 www 3202: $r->print(&hiddenfield('userselhidden','true').
1.106 matthew 3203: '<input type="checkbox" name="showall" onClick="submit()"');
3204: #
1.77 www 3205: if ($ENV{'form.showall'}) {
1.106 matthew 3206: $r->print(' checked');
1.77 www 3207: } else {
1.106 matthew 3208: unless ($ENV{'form.userselhidden'}) {
3209: unless
1.128 matthew 3210: ($ENV{'course.'.$sheet->{'cid'}.'.hideemptyrows'} eq 'yes') {
1.106 matthew 3211: $r->print(' checked');
3212: $ENV{'form.showall'}=1;
3213: }
3214: }
1.77 www 3215: }
1.61 www 3216: $r->print('>');
1.120 matthew 3217: #
3218: # CSV format checkbox (classcalc sheets only)
1.134 matthew 3219: $r->print(' Output as <select name="output" size="1" onClick="submit()">'.
3220: "\n");
1.135 matthew 3221: foreach my $mode (qw/HTML CSV Excel/) {
1.134 matthew 3222: $r->print('<option value="'.$mode.'"');
3223: if ($ENV{'form.output'} eq $mode) {
3224: $r->print(' selected ');
3225: }
3226: $r->print('>'.$mode.'</option>'."\n");
1.135 matthew 3227: }
1.150 matthew 3228: #
3229: # Mulit-sheet excel takes too long and does not work at all for large
3230: # classes. Future inclusion of this option may be possible with the
3231: # Spreadsheet::WriteExcel::Big and speed improvements.
3232: #
3233: # if ($sheet->{'sheettype'} eq 'classcalc') {
3234: # $r->print('<option value="recursive excel"');
3235: # if ($ENV{'form.output'} eq 'recursive excel') {
3236: # $r->print(' selected ');
3237: # }
3238: # $r->print(">Multi-Sheet Excel</option>\n");
3239: # }
1.134 matthew 3240: $r->print("</select>\n");
3241: #
1.119 matthew 3242: if ($sheet->{'sheettype'} eq 'classcalc') {
3243: $r->print(' Student Status: '.
3244: &Apache::lonhtmlcommon::StatusOptions
3245: ($ENV{'form.Status'},'sheet'));
1.69 www 3246: }
1.120 matthew 3247: #
3248: # Buttons to insert rows
1.134 matthew 3249: # $r->print(<<ENDINSERTBUTTONS);
3250: #<br>
3251: #<input type='button' onClick='insertrow("top");'
3252: #value='Insert Row Top'>
3253: #<input type='button' onClick='insertrow("bottom");'
3254: #value='Insert Row Bottom'><br>
3255: #ENDINSERTBUTTONS
1.106 matthew 3256: # Print out sheet
1.143 matthew 3257: &outsheet($sheet,$r);
1.10 www 3258: $r->print('</form></body></html>');
1.106 matthew 3259: # Done
1.3 www 3260: return OK;
1.1 www 3261: }
3262:
3263: 1;
3264: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>