Annotation of loncom/interface/lonspreadsheet.pm, revision 1.150
1.79 matthew 1: #
1.150 ! matthew 2: # $Id: lonspreadsheet.pm,v 1.149 2002/11/22 19:21:59 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') {
968: my $fm=$sheet->{'f'}->{'template_'.$_};
969: $fm=~s/[\'\"]/\&\#34;/g;
1.132 matthew 970: push(@cols,{ name => 'template_'.$_,
971: formula => $fm,
972: value => $fm });
1.122 matthew 973: }
1.132 matthew 974: return ($rowlabel,@cols);
1.122 matthew 975: }
976:
1.16 www 977: sub outrowassess {
1.104 matthew 978: # $n is the current row number
1.132 matthew 979: my ($sheet,$n) = @_;
1.6 www 980: my @cols=();
1.132 matthew 981: my $rowlabel='';
1.6 www 982: if ($n) {
1.122 matthew 983: my ($usy,$ufn)=split(/__&&&\__/,$sheet->{'f'}->{'A'.$n});
1.132 matthew 984: if (exists($sheet->{'rowlabel'}->{$usy})) {
985: $rowlabel = $sheet->{'rowlabel'}->{$usy};
1.104 matthew 986: } else {
1.132 matthew 987: $rowlabel = '';
1.104 matthew 988: }
1.6 www 989: } else {
1.132 matthew 990: $rowlabel = 'Export';
1.6 www 991: }
1.78 matthew 992: foreach ('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',
994: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
995: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.122 matthew 996: my $fm=$sheet->{'f'}->{$_.$n};
1.6 www 997: $fm=~s/[\'\"]/\&\#34;/g;
1.132 matthew 998: push(@cols,{ name => $_.$n,
999: formula => $fm,
1000: value => $sheet->{'values'}->{$_.$n}});
1.78 matthew 1001: }
1.132 matthew 1002: return ($rowlabel,@cols);
1.6 www 1003: }
1004:
1.18 www 1005: sub outrow {
1.132 matthew 1006: my ($sheet,$n)=@_;
1.18 www 1007: my @cols=();
1.132 matthew 1008: my $rowlabel;
1.18 www 1009: if ($n) {
1.132 matthew 1010: $rowlabel = $sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$n}};
1.18 www 1011: } else {
1.132 matthew 1012: if ($sheet->{'sheettype'} eq 'classcalc') {
1013: $rowlabel = 'Summary';
1014: } else {
1015: $rowlabel = 'Export';
1016: }
1.18 www 1017: }
1.78 matthew 1018: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1019: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
1020: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
1021: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.122 matthew 1022: my $fm=$sheet->{'f'}->{$_.$n};
1.118 matthew 1023: $fm=~s/[\'\"]/\&\#34;/g;
1.132 matthew 1024: push(@cols,{ name => $_.$n,
1025: formula => $fm,
1026: value => $sheet->{'values'}->{$_.$n}});
1.118 matthew 1027: }
1.132 matthew 1028: return ($rowlabel,@cols);
1.118 matthew 1029: }
1030:
1.4 www 1031: # ------------------------------------------------ Add or change formula values
1032: sub setformulas {
1.124 matthew 1033: my ($sheet)=shift;
1.119 matthew 1034: %{$sheet->{'safe'}->varglob('f')}=%{$sheet->{'f'}};
1.6 www 1035: }
1036:
1037: # ------------------------------------------------ Add or change formula values
1038: sub setconstants {
1.119 matthew 1039: my ($sheet)=shift;
1.122 matthew 1040: my ($constants) = @_;
1041: if (! ref($constants)) {
1042: my %tmp = @_;
1043: $constants = \%tmp;
1044: }
1045: $sheet->{'constants'} = $constants;
1.119 matthew 1046: return %{$sheet->{'safe'}->varglob('c')}=%{$sheet->{'constants'}};
1.6 www 1047: }
1048:
1.55 www 1049: # --------------------------------------------- Set names of other spreadsheets
1050: sub setothersheets {
1.119 matthew 1051: my $sheet = shift;
1052: my @othersheets = @_;
1053: $sheet->{'othersheets'} = \@othersheets;
1054: @{$sheet->{'safe'}->varglob('os')}=@othersheets;
1055: return;
1.55 www 1056: }
1057:
1.6 www 1058: # ------------------------------------------------ Add or change formula values
1059: sub setrowlabels {
1.119 matthew 1060: my $sheet=shift;
1.125 matthew 1061: my ($rowlabel) = @_;
1062: if (! ref($rowlabel)) {
1063: my %tmp = @_;
1064: $rowlabel = \%tmp;
1065: }
1066: $sheet->{'rowlabel'}=$rowlabel;
1.4 www 1067: }
1068:
1069: # ------------------------------------------------------- Calculate spreadsheet
1070: sub calcsheet {
1.119 matthew 1071: my $sheet=shift;
1.124 matthew 1072: my $result = $sheet->{'safe'}->reval('&calc();');
1073: %{$sheet->{'values'}} = %{$sheet->{'safe'}->varglob('sheet_values')};
1074: return $result;
1.4 www 1075: }
1076:
1077: # ---------------------------------------------------------------- Get formulas
1.131 matthew 1078: # Return a copy of the formulas
1.4 www 1079: sub getformulas {
1.119 matthew 1080: my $sheet = shift;
1081: return %{$sheet->{'safe'}->varglob('f')};
1.4 www 1082: }
1083:
1.132 matthew 1084: sub geterrorlog {
1085: my $sheet = shift;
1086: return ${$sheet->{'safe'}->varglob('errorlog')};
1087: }
1088:
1.139 matthew 1089: sub gettitle {
1090: my $sheet = shift;
1091: if ($sheet->{'sheettype'} eq 'classcalc') {
1092: return $sheet->{'coursedesc'};
1093: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1094: return 'Grades for '.$sheet->{'uname'}.'@'.$sheet->{'udom'};
1095: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1096: if (($sheet->{'usymb'} eq '_feedback') ||
1097: ($sheet->{'usymb'} eq '_evaluation') ||
1098: ($sheet->{'usymb'} eq '_discussion') ||
1099: ($sheet->{'usymb'} eq '_tutoring')) {
1100: my $title = $sheet->{'usymb'};
1101: $title =~ s/^_//;
1102: $title = ucfirst($title);
1103: return $title;
1104: }
1105: return if (! defined($sheet->{'mapid'}) ||
1106: $sheet->{'mapid'} !~ /^\d+$/);
1107: my $mapid = $sheet->{'mapid'};
1108: return if (! defined($sheet->{'resid'}) ||
1109: $sheet->{'resid'} !~ /^\d+$/);
1110: my $resid = $sheet->{'resid'};
1111: my %course_db;
1112: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
1113: &GDBM_READER(),0640);
1114: return if (! tied(%course_db));
1115: my $key = 'title_'.$mapid.'.'.$resid;
1116: my $title = '';
1117: if (exists($course_db{$key})) {
1118: $title = $course_db{$key};
1119: } else {
1120: $title = $sheet->{'usymb'};
1121: }
1122: untie (%course_db);
1123: return $title;
1124: }
1125: }
1126:
1.97 www 1127: # ----------------------------------------------------- Get value of $f{'A'.$n}
1128: sub getfa {
1.119 matthew 1129: my $sheet = shift;
1130: my ($n)=@_;
1131: return $sheet->{'safe'}->reval('$f{"A'.$n.'"}');
1.97 www 1132: }
1133:
1.14 www 1134: # ------------------------------------------------------------- Export of A-row
1.28 www 1135: sub exportdata {
1.119 matthew 1136: my $sheet=shift;
1.121 matthew 1137: my @exportarray=();
1138: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1139: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.130 matthew 1140: if (exists($sheet->{'values'}->{$_.'0'})) {
1141: push(@exportarray,$sheet->{'values'}->{$_.'0'});
1142: } else {
1143: push(@exportarray,'');
1144: }
1.121 matthew 1145: }
1146: return @exportarray;
1.14 www 1147: }
1.55 www 1148:
1.136 matthew 1149:
1150:
1151: sub update_student_sheet{
1.143 matthew 1152: my ($sheet,$r,$c) = @_;
1.136 matthew 1153: # Load in the studentcalc sheet
1154: &readsheet($sheet,'default_studentcalc');
1155: # Determine the structure (contained assessments, etc) of the sheet
1156: &updatesheet($sheet);
1157: # Load in the cached sheets for this student
1158: &cachedssheets($sheet);
1159: # Load in the (possibly cached) data from the assessment sheets
1.143 matthew 1160: &loadstudent($sheet,$r,$c);
1.136 matthew 1161: # Compute the sheet
1162: &calcsheet($sheet);
1163: }
1164:
1.5 www 1165: # ========================================================== End of Spreadsheet
1166: # =============================================================================
1.27 www 1167: #
1.135 matthew 1168: # Procedures for spreadsheet output
1.27 www 1169: #
1.6 www 1170: # --------------------------------------------- Produce output row n from sheet
1171:
1.132 matthew 1172: sub get_row {
1173: my ($sheet,$n) = @_;
1174: my ($rowlabel,@rowdata);
1.104 matthew 1175: if ($n eq '-') {
1.132 matthew 1176: ($rowlabel,@rowdata) = &templaterow($sheet);
1177: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1178: ($rowlabel,@rowdata) = &outrowassess($sheet,$n);
1.61 www 1179: } else {
1.132 matthew 1180: ($rowlabel,@rowdata) = &outrow($sheet,$n);
1.61 www 1181: }
1.132 matthew 1182: return ($rowlabel,@rowdata);
1.6 www 1183: }
1184:
1.132 matthew 1185: ########################################################################
1186: ########################################################################
1187: sub sort_indicies {
1188: my $sheet = shift;
1.142 matthew 1189: my @sortidx=();
1.106 matthew 1190: #
1.142 matthew 1191: if ($sheet->{'sheettype'} eq 'classcalc') {
1.143 matthew 1192: my @sortby=(undef);
1.142 matthew 1193: # Skip row 0
1194: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1195: my (undef,$sname,$sdom,$fullname,$section,$id) =
1196: split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
1197: push (@sortby, lc($fullname));
1198: push (@sortidx, $row);
1199: }
1200: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1201: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.143 matthew 1202: my @sortby1=(undef);
1203: my @sortby2=(undef);
1.142 matthew 1204: # Skip row 0
1205: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1206: my (undef,$symb,$uname,$udom,$mapid,$resid,$title) =
1207: split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
1208: $symb = &Apache::lonnet::unescape($symb);
1209: my ($sequence) = ($symb =~ /\/([^\/]*\.sequence)/);
1210: if ($sequence eq '') {
1211: $sequence = $symb;
1212: }
1.143 matthew 1213: push (@sortby1, $sequence);
1214: push (@sortby2, $title);
1.142 matthew 1215: push (@sortidx, $row);
1216: }
1.143 matthew 1217: @sortidx = sort { $sortby1[$a] cmp $sortby1[$b] ||
1218: $sortby2[$a] cmp $sortby2[$b] } @sortidx;
1.142 matthew 1219: } else {
1.143 matthew 1220: my @sortby=(undef);
1.142 matthew 1221: # Skip row 0
1222: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1223: push (@sortby, $sheet->{'safe'}->reval('$f{"A'.$row.'"}'));
1224: push (@sortidx, $row);
1225: }
1226: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1.65 www 1227: }
1.132 matthew 1228: return @sortidx;
1229: }
1230:
1.135 matthew 1231: #############################################################
1232: ### ###
1233: ### Spreadsheet Output Routines ###
1234: ### ###
1235: #############################################################
1236:
1237: ############################################
1238: ## HTML output routines ##
1239: ############################################
1.132 matthew 1240: sub html_editable_cell {
1241: my ($cell,$bgcolor) = @_;
1242: my $result;
1243: my ($name,$formula,$value);
1244: if (defined($cell)) {
1245: $name = $cell->{'name'};
1246: $formula = $cell->{'formula'};
1247: $value = $cell->{'value'};
1248: }
1249: $name = '' if (! defined($name));
1250: $formula = '' if (! defined($formula));
1251: if (! defined($value)) {
1252: $value = '<font color="'.$bgcolor.'">#</font>';
1253: if ($formula ne '') {
1254: $value = '<i>undefined value</i>';
1255: }
1256: }
1.133 matthew 1257: if ($value =~ /^\s*$/ ) {
1258: $value = '<font color="'.$bgcolor.'">#</font>';
1259: }
1.138 matthew 1260: $formula =~ s/\n/\\n/gs;
1.132 matthew 1261: $result .= '<a href="javascript:celledit(\''.
1262: $name.'\',\''.$formula.'\');">'.$value.'</a>';
1263: return $result;
1264: }
1265:
1266: sub html_uneditable_cell {
1267: my ($cell,$bgcolor) = @_;
1268: my $value = (defined($cell) ? $cell->{'value'} : '');
1269: return ' '.$value.' ';
1270: }
1271:
1272: sub outsheet_html {
1273: my ($sheet,$r) = @_;
1274: my ($num_uneditable,$realm,$row_type);
1.119 matthew 1275: if ($sheet->{'sheettype'} eq 'assesscalc') {
1.132 matthew 1276: $num_uneditable = 1;
1277: $realm = 'Assessment';
1278: $row_type = 'Item';
1.119 matthew 1279: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.132 matthew 1280: $num_uneditable = 26;
1281: $realm = 'User';
1282: $row_type = 'Assessment';
1283: } elsif ($sheet->{'sheettype'} eq 'classcalc') {
1284: $num_uneditable = 26;
1285: $realm = 'Course';
1286: $row_type = 'Student';
1287: } else {
1288: return; # error
1289: }
1290: ####################################
1291: # Print out header table
1292: ####################################
1293: my $num_left = 52-$num_uneditable;
1294: my $tabledata =<<"END";
1295: <table border="2">
1296: <tr>
1297: <th colspan="1" rowspan="2"><font size="+2">$realm</font></th>
1298: <td bgcolor="#FFDDDD" colspan="$num_uneditable">
1299: <b><font size="+1">Import</font></b></td>
1300: <td colspan="$num_left">
1301: <b><font size="+1">Calculations</font></b></td>
1302: </tr><tr>
1303: END
1304: my $label_num = 0;
1305: foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
1306: if ($label_num<$num_uneditable) {
1307: $tabledata.='<td bgcolor="#FFDDDD">';
1308: } else {
1309: $tabledata.='<td>';
1310: }
1311: $tabledata.="<b><font size=+1>$_</font></b></td>";
1312: $label_num++;
1.106 matthew 1313: }
1.132 matthew 1314: $tabledata.="</tr>\n";
1315: $r->print($tabledata);
1316: ####################################
1317: # Print out template row
1318: ####################################
1319: my ($rowlabel,@rowdata) = &get_row($sheet,'-');
1.149 matthew 1320: my $row_html = '<tr><td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1321: my $num_cols_output = 0;
1322: foreach my $cell (@rowdata) {
1323: if ($num_cols_output++ < $num_uneditable) {
1324: $row_html .= '<td bgcolor="#FFDDDD">';
1325: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
1326: } else {
1327: $row_html .= '<td bgcolor="#EOFFDD">';
1328: $row_html .= &html_editable_cell($cell,'#E0FFDD');
1329: }
1330: $row_html .= '</td>';
1331: }
1332: $row_html.= "</tr>\n";
1333: $r->print($row_html);
1334: ####################################
1335: # Print out summary/export row
1336: ####################################
1337: my ($rowlabel,@rowdata) = &get_row($sheet,'0');
1.149 matthew 1338: $row_html = '<tr><td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1339: $num_cols_output = 0;
1340: foreach my $cell (@rowdata) {
1341: if ($num_cols_output++ < 26) {
1342: $row_html .= '<td bgcolor="#CCCCFF">';
1343: $row_html .= &html_editable_cell($cell,'#CCCCFF');
1344: } else {
1345: $row_html .= '<td bgcolor="#DDCCFF">';
1346: $row_html .= &html_uneditable_cell(undef,'#CCCCFF');
1347: }
1348: $row_html .= '</td>';
1349: }
1350: $row_html.= "</tr>\n";
1351: $r->print($row_html);
1352: $r->print('</table>');
1353: ####################################
1354: # Prepare to output rows
1355: ####################################
1356: my @Rows = &sort_indicies($sheet);
1.106 matthew 1357: #
1358: # Loop through the rows and output them one at a time
1.132 matthew 1359: my $rows_output=0;
1360: foreach my $rownum (@Rows) {
1361: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1.136 matthew 1362: next if ($rowlabel =~ /^\s*$/);
1.141 matthew 1363: next if (($sheet->{'sheettype'} eq 'assesscalc') &&
1364: (! $ENV{'form.showall'}) &&
1365: ($rowdata[0]->{'value'} =~ /^\s*$/));
1.143 matthew 1366: if (! $ENV{'form.showall'} &&
1367: $sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
1.141 matthew 1368: my $row_is_empty = 1;
1369: foreach my $cell (@rowdata) {
1370: if ($cell->{'value'} !~ /^\s*$/) {
1371: $row_is_empty = 0;
1372: last;
1373: }
1374: }
1.143 matthew 1375: next if ($row_is_empty);
1.141 matthew 1376: }
1.132 matthew 1377: #
1378: my $defaultbg='#E0FF';
1379: #
1380: my $row_html ="\n".'<tr><td><b><font size=+1>'.$rownum.
1381: '</font></b></td>';
1382: #
1383: if ($sheet->{'sheettype'} eq 'classcalc') {
1.149 matthew 1384: $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1385: # Output links for each student?
1.133 matthew 1386: # Nope, that is already done for us in format_html_rowlabel (for now)
1.132 matthew 1387: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.149 matthew 1388: $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel);
1.132 matthew 1389: $row_html.= '<br>'.
1390: '<select name="sel_'.$rownum.'" '.
1391: 'onChange="changesheet('.$rownum.')">'.
1392: '<option name="default">Default</option>';
1393: foreach (@{$sheet->{'othersheets'}}) {
1394: $row_html.='<option name="'.$_.'"';
1395: #if ($ufn eq $_) {
1396: # $row_html.=' selected';
1397: #}
1398: $row_html.='>'.$_.'</option>';
1399: }
1400: $row_html.='</select></td>';
1401: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1.149 matthew 1402: $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
1.132 matthew 1403: }
1404: #
1405: my $shown_cells = 0;
1406: foreach my $cell (@rowdata) {
1407: my $value = $cell->{'value'};
1408: my $formula = $cell->{'formula'};
1409: my $cellname = $cell->{'name'};
1410: #
1411: my $bgcolor;
1412: if ($shown_cells && ($shown_cells/5 == int($shown_cells/5))) {
1413: $bgcolor = $defaultbg.'99';
1414: } else {
1415: $bgcolor = $defaultbg.'DD';
1416: }
1417: $bgcolor='#FFDDDD' if ($shown_cells < $num_uneditable);
1418: #
1419: $row_html.='<td bgcolor='.$bgcolor.'>';
1420: if ($shown_cells < $num_uneditable) {
1421: $row_html .= &html_uneditable_cell($cell,$bgcolor);
1422: } else {
1423: $row_html .= &html_editable_cell($cell,$bgcolor);
1424: }
1425: $row_html.='</td>';
1426: $shown_cells++;
1427: }
1428: if ($row_html) {
1429: if ($rows_output % 25 == 0) {
1.102 matthew 1430: $r->print("</table>\n<br>\n");
1431: $r->rflush();
1.132 matthew 1432: $r->print('<table border=2>'.
1433: '<tr><td> <td>'.$row_type.'</td>'.
1434: '<td>'.
1.106 matthew 1435: join('</td><td>',
1436: (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
1437: 'abcdefghijklmnopqrstuvwxyz'))).
1.102 matthew 1438: "</td></tr>\n");
1439: }
1.132 matthew 1440: $rows_output++;
1441: $r->print($row_html);
1.78 matthew 1442: }
1.6 www 1443: }
1.132 matthew 1444: #
1445: $r->print('</table>');
1446: #
1447: # Debugging code (be sure to uncomment errorlog code in safe space):
1448: #
1449: # $r->print("\n<pre>");
1450: # $r->print(&geterrorlog($sheet));
1451: # $r->print("\n</pre>");
1452: return 1;
1453: }
1454:
1.135 matthew 1455: ############################################
1456: ## csv output routines ##
1457: ############################################
1.132 matthew 1458: sub outsheet_csv {
1459: my ($sheet,$r) = @_;
1.133 matthew 1460: my $csvdata = '';
1461: my @Values;
1462: ####################################
1463: # Prepare to output rows
1464: ####################################
1465: my @Rows = &sort_indicies($sheet);
1466: #
1467: # Loop through the rows and output them one at a time
1468: my $rows_output=0;
1469: foreach my $rownum (@Rows) {
1470: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1.136 matthew 1471: next if ($rowlabel =~ /^\s*$/);
1.149 matthew 1472: push (@Values,&format_csv_rowlabel($sheet,$rowlabel));
1.133 matthew 1473: foreach my $cell (@rowdata) {
1474: push (@Values,'"'.$cell->{'value'}.'"');
1475: }
1476: $csvdata.= join(',',@Values)."\n";
1477: @Values = ();
1478: }
1479: #
1.134 matthew 1480: # Write the CSV data to a file and serve up a link
1481: #
1482: my $filename = '/prtspool/'.
1483: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1484: time.'_'.rand(1000000000).'.csv';
1485: my $file;
1486: unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
1487: $r->log_error("Couldn't open $filename for output $!");
1488: $r->print("Problems occured in writing the csv file. ".
1489: "This error has been logged. ".
1490: "Please alert your LON-CAPA administrator.");
1491: $r->print("<pre>\n".$csvdata."</pre>\n");
1492: return 0;
1493: }
1494: print $file $csvdata;
1495: close($file);
1496: $r->print('<br /><br />'.
1497: '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
1.133 matthew 1498: #
1499: return 1;
1.132 matthew 1500: }
1501:
1.135 matthew 1502: ############################################
1503: ## Excel output routines ##
1504: ############################################
1505: sub outsheet_recursive_excel {
1506: my ($sheet,$r) = @_;
1.136 matthew 1507: my $c = $r->connection;
1.135 matthew 1508: return undef if ($sheet->{'sheettype'} ne 'classcalc');
1509: my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
1510: return undef if (! defined($workbook));
1511: #
1512: # Create main worksheet
1513: my $main_worksheet = $workbook->addworksheet('main');
1514: #
1515: # Figure out who the students are
1516: my %f=&getformulas($sheet);
1517: my $count = 0;
1.136 matthew 1518: $r->print(<<END);
1519: <p>
1520: Compiling Excel Workbook with a worksheet for each student.
1521: </p><p>
1522: This operation may take longer than a complete recalculation of the
1523: spreadsheet.
1524: </p><p>
1525: To abort this operation, hit the stop button on your browser.
1526: </p><p>
1527: A link to the spreadsheet will be available at the end of this process.
1528: </p>
1529: <p>
1530: END
1.135 matthew 1531: $r->rflush();
1.136 matthew 1532: my $starttime = time;
1.146 matthew 1533: foreach my $rownum (&sort_indicies($sheet)) {
1.135 matthew 1534: $count++;
1.146 matthew 1535: my ($sname,$sdom) = split(':',$f{'A'.$rownum});
1.135 matthew 1536: my $student_excel_worksheet=$workbook->addworksheet($sname.'@'.$sdom);
1537: # Create a new spreadsheet
1538: my $studentsheet = &makenewsheet($sname,$sdom,'studentcalc',undef);
1539: # Read in the spreadsheet definition
1.143 matthew 1540: &update_student_sheet($studentsheet,$r,$c);
1.135 matthew 1541: # Stuff the sheet into excel
1542: &export_sheet_as_excel($studentsheet,$student_excel_worksheet);
1.136 matthew 1543: my $totaltime = int((time - $starttime) / $count * $sheet->{'maxrow'});
1544: my $timeleft = int((time - $starttime) / $count * ($sheet->{'maxrow'} - $count));
1.135 matthew 1545: if ($count % 5 == 0) {
1.136 matthew 1546: $r->print($count.' students completed.'.
1547: ' Time remaining: '.$timeleft.' sec. '.
1548: ' Estimated total time: '.$totaltime." sec <br />\n");
1.135 matthew 1549: $r->rflush();
1550: }
1.136 matthew 1551: if(defined($c) && ($c->aborted())) {
1552: last;
1553: }
1.135 matthew 1554: }
1555: #
1.136 matthew 1556: if(! $c->aborted() ) {
1557: $r->print('All students spreadsheets completed!<br />');
1558: $r->rflush();
1559: #
1560: # &export_sheet_as_excel fills $worksheet with the data from $sheet
1561: &export_sheet_as_excel($sheet,$main_worksheet);
1562: #
1563: $workbook->close();
1564: # Okay, the spreadsheet is taken care of, so give the user a link.
1565: $r->print('<br /><br />'.
1566: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1567: } else {
1568: $workbook->close(); # Not sure how necessary this is.
1569: #unlink('/home/httpd'.$filename); # No need to keep this around?
1570: }
1.135 matthew 1571: return 1;
1572: }
1573:
1.132 matthew 1574: sub outsheet_excel {
1575: my ($sheet,$r) = @_;
1.135 matthew 1576: my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
1577: return undef if (! defined($workbook));
1578: my $sheetname;
1579: if ($sheet->{'sheettype'} eq 'classcalc') {
1580: $sheetname = 'Main';
1581: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1582: $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'};
1583: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1584: $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'}.' assessment';
1585: }
1586: my $worksheet = $workbook->addworksheet($sheetname);
1587: #
1588: # &export_sheet_as_excel fills $worksheet with the data from $sheet
1589: &export_sheet_as_excel($sheet,$worksheet);
1590: #
1591: $workbook->close();
1592: # Okay, the spreadsheet is taken care of, so give the user a link.
1593: $r->print('<br /><br />'.
1594: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1595: return 1;
1596: }
1597:
1598: sub create_excel_spreadsheet {
1599: my ($sheet,$r) = @_;
1.134 matthew 1600: my $filename = '/prtspool/'.
1601: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1602: time.'_'.rand(1000000000).'.xls';
1603: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1604: if (! defined($workbook)) {
1605: $r->log_error("Error creating excel spreadsheet $filename: $!");
1606: $r->print("Problems creating new Excel file. ".
1607: "This error has been logged. ".
1608: "Please alert your LON-CAPA administrator");
1.135 matthew 1609: return undef;
1.134 matthew 1610: }
1611: #
1612: # The spreadsheet stores temporary data in files, then put them
1613: # together. If needed we should be able to disable this (memory only).
1614: # The temporary directory must be specified before calling 'addworksheet'.
1615: # File::Temp is used to determine the temporary directory.
1616: $workbook->set_tempdir('/home/httpd/perl/tmp');
1617: #
1618: # Determine the name to give the worksheet
1.135 matthew 1619: return ($workbook,$filename);
1620: }
1621:
1622: sub export_sheet_as_excel {
1623: my $sheet = shift;
1624: my $worksheet = shift;
1.139 matthew 1625: #
1626: my $rows_output = 0;
1627: my $cols_output = 0;
1628: ####################################
1629: # Write an identifying row #
1630: ####################################
1631: my @Headerinfo = ($sheet->{'coursedesc'});
1632: my $title = &gettitle($sheet);
1633: $cols_output = 0;
1634: if (defined($title)) {
1635: $worksheet->write($rows_output++,$cols_output++,$title);
1636: }
1637: ####################################
1638: # Write the summary/export row #
1639: ####################################
1640: my ($rowlabel,@rowdata) = &get_row($sheet,'0');
1.149 matthew 1641: my $label = &format_excel_rowlabel($sheet,$rowlabel);
1.139 matthew 1642: $cols_output = 0;
1643: $worksheet->write($rows_output,$cols_output++,$label);
1644: foreach my $cell (@rowdata) {
1645: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1646: }
1647: $rows_output+= 2; # Skip a row, just for fun
1.134 matthew 1648: ####################################
1649: # Prepare to output rows
1650: ####################################
1651: my @Rows = &sort_indicies($sheet);
1652: #
1653: # Loop through the rows and output them one at a time
1654: foreach my $rownum (@Rows) {
1655: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1.143 matthew 1656: next if ($rowlabel =~ /^[\s]*$/);
1.139 matthew 1657: $cols_output = 0;
1.149 matthew 1658: my $label = &format_excel_rowlabel($sheet,$rowlabel);
1.143 matthew 1659: if ( ! $ENV{'form.showall'} &&
1660: $sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
1661: my $row_is_empty = 1;
1662: foreach my $cell (@rowdata) {
1663: if ($cell->{'value'} !~ /^\s*$/) {
1664: $row_is_empty = 0;
1665: last;
1666: }
1667: }
1668: next if ($row_is_empty);
1669: }
1.134 matthew 1670: $worksheet->write($rows_output,$cols_output++,$label);
1671: if (ref($label)) {
1672: $cols_output = (scalar(@$label));
1673: }
1674: foreach my $cell (@rowdata) {
1.139 matthew 1675: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1.134 matthew 1676: }
1677: $rows_output++;
1678: }
1.135 matthew 1679: return;
1.132 matthew 1680: }
1681:
1.135 matthew 1682: ############################################
1683: ## XML output routines ##
1684: ############################################
1.132 matthew 1685: sub outsheet_xml {
1686: my ($sheet,$r) = @_;
1.135 matthew 1687: ## Someday XML
1688: ## Will be rendered for the user
1689: ## But not on this day
1.6 www 1690: }
1691:
1.135 matthew 1692: ##
1693: ## Outsheet - calls other outsheet_* functions
1694: ##
1.132 matthew 1695: sub outsheet {
1.143 matthew 1696: my ($sheet,$r)=@_;
1.134 matthew 1697: if (! exists($ENV{'form.output'})) {
1698: $ENV{'form.output'} = 'HTML';
1699: }
1700: if (lc($ENV{'form.output'}) eq 'csv') {
1.133 matthew 1701: &outsheet_csv($sheet,$r);
1.134 matthew 1702: } elsif (lc($ENV{'form.output'}) eq 'excel') {
1703: &outsheet_excel($sheet,$r);
1.135 matthew 1704: } elsif (lc($ENV{'form.output'}) eq 'recursive excel') {
1705: &outsheet_recursive_excel($sheet,$r);
1.134 matthew 1706: # } elsif (lc($ENV{'form.output'}) eq 'xml' ) {
1.132 matthew 1707: # &outsheet_xml($sheet,$r);
1.133 matthew 1708: } else {
1709: &outsheet_html($sheet,$r);
1710: }
1.132 matthew 1711: }
1712:
1713: ########################################################################
1714: ########################################################################
1.55 www 1715: sub othersheets {
1.119 matthew 1716: my ($sheet,$stype)=@_;
1717: $stype = $sheet->{'sheettype'} if (! defined($stype));
1.81 matthew 1718: #
1.119 matthew 1719: my $cnum = $sheet->{'cnum'};
1720: my $cdom = $sheet->{'cdom'};
1721: my $chome = $sheet->{'chome'};
1.81 matthew 1722: #
1.55 www 1723: my @alternatives=();
1.81 matthew 1724: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
1725: my ($tmp) = keys(%results);
1726: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1727: @alternatives = sort (keys(%results));
1728: }
1.55 www 1729: return @alternatives;
1730: }
1731:
1.82 matthew 1732: #
1733: # -------------------------------------- Parse a spreadsheet
1734: #
1735: sub parse_sheet {
1736: # $sheetxml is a scalar reference or a scalar
1737: my ($sheetxml) = @_;
1738: if (! ref($sheetxml)) {
1739: my $tmp = $sheetxml;
1740: $sheetxml = \$tmp;
1741: }
1742: my %f;
1743: my $parser=HTML::TokeParser->new($sheetxml);
1744: my $token;
1745: while ($token=$parser->get_token) {
1746: if ($token->[0] eq 'S') {
1747: if ($token->[1] eq 'field') {
1748: $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
1749: $parser->get_text('/field');
1750: }
1751: if ($token->[1] eq 'template') {
1752: $f{'template_'.$token->[2]->{'col'}}=
1753: $parser->get_text('/template');
1754: }
1755: }
1756: }
1757: return \%f;
1758: }
1759:
1.55 www 1760: #
1.27 www 1761: # -------------------------------------- Read spreadsheet formulas for a course
1762: #
1763: sub readsheet {
1.119 matthew 1764: my ($sheet,$fn)=@_;
1.107 matthew 1765: #
1.119 matthew 1766: my $stype = $sheet->{'sheettype'};
1767: my $cnum = $sheet->{'cnum'};
1768: my $cdom = $sheet->{'cdom'};
1769: my $chome = $sheet->{'chome'};
1.107 matthew 1770: #
1.104 matthew 1771: if (! defined($fn)) {
1772: # There is no filename. Look for defaults in course and global, cache
1773: unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
1774: my %tmphash = &Apache::lonnet::get('environment',
1775: ['spreadsheet_default_'.$stype],
1776: $cdom,$cnum);
1777: my ($tmp) = keys(%tmphash);
1778: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1779: $fn = 'default_'.$stype;
1780: } else {
1781: $fn = $tmphash{'spreadsheet_default_'.$stype};
1782: }
1783: unless (($fn) && ($fn!~/^error\:/)) {
1784: $fn='default_'.$stype;
1785: }
1786: $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn;
1787: }
1788: }
1789: # $fn now has a value
1.119 matthew 1790: $sheet->{'filename'} = $fn;
1.104 matthew 1791: # see if sheet is cached
1792: my $fstring='';
1793: if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
1.119 matthew 1794: my %tmp = split(/___;___/,$fstring);
1.124 matthew 1795: $sheet->{'f'} = \%tmp;
1796: &setformulas($sheet);
1.104 matthew 1797: } else {
1798: # Not cached, need to read
1799: my %f=();
1800: if ($fn=~/^default\_/) {
1801: my $sheetxml='';
1802: my $fh;
1803: my $dfn=$fn;
1804: $dfn=~s/\_/\./g;
1805: if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
1806: $sheetxml=join('',<$fh>);
1807: } else {
1.141 matthew 1808: # $sheetxml='<field row="0" col="A">"Error"</field>';
1809: $sheetxml='<field row="0" col="A"></field>';
1.104 matthew 1810: }
1811: %f=%{&parse_sheet(\$sheetxml)};
1812: } elsif($fn=~/\/*\.spreadsheet$/) {
1813: my $sheetxml=&Apache::lonnet::getfile
1814: (&Apache::lonnet::filelocation('',$fn));
1815: if ($sheetxml == -1) {
1816: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
1817: .$fn.'"</field>';
1818: }
1819: %f=%{&parse_sheet(\$sheetxml)};
1820: } else {
1821: my $sheet='';
1822: my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
1823: my ($tmp) = keys(%tmphash);
1824: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1825: foreach (keys(%tmphash)) {
1826: $f{$_}=$tmphash{$_};
1827: }
1828: }
1829: }
1830: # Cache and set
1831: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1.124 matthew 1832: $sheet->{'f'}=\%f;
1833: &setformulas($sheet);
1.3 www 1834: }
1835: }
1836:
1.28 www 1837: # -------------------------------------------------------- Make new spreadsheet
1838: sub makenewsheet {
1839: my ($uname,$udom,$stype,$usymb)=@_;
1.119 matthew 1840: my $sheet={};
1841: $sheet->{'uname'} = $uname;
1842: $sheet->{'udom'} = $udom;
1843: $sheet->{'sheettype'} = $stype;
1844: $sheet->{'usymb'} = $usymb;
1.139 matthew 1845: $sheet->{'mapid'} = $ENV{'form.mapid'};
1846: $sheet->{'resid'} = $ENV{'form.resid'};
1.119 matthew 1847: $sheet->{'cid'} = $ENV{'request.course.id'};
1848: $sheet->{'csec'} = $Section{$uname.':'.$udom};
1849: $sheet->{'coursefilename'} = $ENV{'request.course.fn'};
1850: $sheet->{'cnum'} = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1851: $sheet->{'cdom'} = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1852: $sheet->{'chome'} = $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.134 matthew 1853: $sheet->{'coursedesc'} = $ENV{'course.'.$ENV{'request.course.id'}.
1.139 matthew 1854: '.description'};
1.119 matthew 1855: $sheet->{'uhome'} = &Apache::lonnet::homeserver($uname,$udom);
1856: #
1857: #
1858: $sheet->{'f'} = {};
1859: $sheet->{'constants'} = {};
1860: $sheet->{'othersheets'} = [];
1861: $sheet->{'rowlabel'} = {};
1862: #
1863: #
1864: $sheet->{'safe'}=&initsheet($sheet->{'sheettype'});
1.116 matthew 1865: #
1.119 matthew 1866: # Place all the %$sheet items into the safe space except the safe space
1867: # itself
1.105 matthew 1868: my $initstring = '';
1.119 matthew 1869: foreach (qw/uname udom sheettype usymb cid csec coursefilename
1870: cnum cdom chome uhome/) {
1871: $initstring.= qq{\$$_="$sheet->{$_}";};
1.105 matthew 1872: }
1.119 matthew 1873: $sheet->{'safe'}->reval($initstring);
1874: return $sheet;
1.28 www 1875: }
1876:
1.19 www 1877: # ------------------------------------------------------------ Save spreadsheet
1878: sub writesheet {
1.119 matthew 1879: my ($sheet,$makedef)=@_;
1880: my $cid=$sheet->{'cid'};
1.104 matthew 1881: if (&Apache::lonnet::allowed('opa',$cid)) {
1.119 matthew 1882: my %f=&getformulas($sheet);
1883: my $stype= $sheet->{'sheettype'};
1884: my $cnum = $sheet->{'cnum'};
1885: my $cdom = $sheet->{'cdom'};
1886: my $chome= $sheet->{'chome'};
1887: my $fn = $sheet->{'filename'};
1.104 matthew 1888: # Cache new sheet
1889: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1890: # Write sheet
1891: foreach (keys(%f)) {
1.131 matthew 1892: delete($f{$_}) if ($f{$_} eq 'import');
1.104 matthew 1893: }
1.131 matthew 1894: my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
1.104 matthew 1895: if ($reply eq 'ok') {
1.131 matthew 1896: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
1897: {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
1898: $cdom,$cnum);
1.104 matthew 1899: if ($reply eq 'ok') {
1900: if ($makedef) {
1.131 matthew 1901: return &Apache::lonnet::put('environment',
1902: {'spreadsheet_default_'.$stype => $fn },
1903: $cdom,$cnum);
1.104 matthew 1904: }
1905: return $reply;
1906: }
1907: return $reply;
1908: }
1909: return $reply;
1910: }
1911: return 'unauthorized';
1.19 www 1912: }
1913:
1.10 www 1914: # ----------------------------------------------- Make a temp copy of the sheet
1.28 www 1915: # "Modified workcopy" - interactive only
1916: #
1.10 www 1917: sub tmpwrite {
1.119 matthew 1918: my ($sheet) = @_;
1.28 www 1919: my $fn=$ENV{'user.name'}.'_'.
1.119 matthew 1920: $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
1921: $sheet->{'filename'};
1.10 www 1922: $fn=~s/\W/\_/g;
1923: $fn=$tmpdir.$fn.'.tmp';
1924: my $fh;
1925: if ($fh=Apache::File->new('>'.$fn)) {
1.119 matthew 1926: print $fh join("\n",&getformulas($sheet));
1.10 www 1927: }
1928: }
1929:
1930: # ---------------------------------------------------------- Read the temp copy
1931: sub tmpread {
1.119 matthew 1932: my ($sheet,$nfield,$nform)=@_;
1.28 www 1933: my $fn=$ENV{'user.name'}.'_'.
1.119 matthew 1934: $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
1935: $sheet->{'filename'};
1.10 www 1936: $fn=~s/\W/\_/g;
1937: $fn=$tmpdir.$fn.'.tmp';
1938: my $fh;
1939: my %fo=();
1.92 www 1940: my $countrows=0;
1.10 www 1941: if ($fh=Apache::File->new($fn)) {
1942: my $name;
1943: while ($name=<$fh>) {
1944: chomp($name);
1945: my $value=<$fh>;
1946: chomp($value);
1947: $fo{$name}=$value;
1.93 www 1948: if ($name=~/^A(\d+)$/) {
1949: if ($1>$countrows) {
1950: $countrows=$1;
1951: }
1952: }
1.10 www 1953: }
1954: }
1.55 www 1955: if ($nform eq 'changesheet') {
1.128 matthew 1956: $fo{'A'.$nfield}=(split(/__&&&\__/,$fo{'A'.$nfield}))[0];
1.55 www 1957: unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
1.57 www 1958: $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
1.55 www 1959: }
1.92 www 1960: } elsif ($nfield eq 'insertrow') {
1.93 www 1961: $countrows++;
1.95 www 1962: my $newrow=substr('000000'.$countrows,-7);
1.92 www 1963: if ($nform eq 'top') {
1.94 www 1964: $fo{'A'.$countrows}='--- '.$newrow;
1.92 www 1965: } else {
1.94 www 1966: $fo{'A'.$countrows}='~~~ '.$newrow;
1.92 www 1967: }
1.55 www 1968: } else {
1969: if ($nfield) { $fo{$nfield}=$nform; }
1970: }
1.124 matthew 1971: $sheet->{'f'}=\%fo;
1972: &setformulas($sheet);
1.10 www 1973: }
1974:
1.104 matthew 1975: ##################################################
1976: ##################################################
1.11 www 1977:
1.104 matthew 1978: =pod
1.11 www 1979:
1.104 matthew 1980: =item &parmval()
1.11 www 1981:
1.104 matthew 1982: Determine the value of a parameter.
1.11 www 1983:
1.119 matthew 1984: Inputs: $what, the parameter needed, $sheet, the safe space
1.11 www 1985:
1.104 matthew 1986: Returns: The value of a parameter, or '' if none.
1.11 www 1987:
1.104 matthew 1988: This function cascades through the possible levels searching for a value for
1989: a parameter. The levels are checked in the following order:
1990: user, course (at section level and course level), map, and lonnet::metadata.
1991: This function uses %parmhash, which must be tied prior to calling it.
1992: This function also requires %courseopt and %useropt to be initialized for
1993: this user and course.
1.11 www 1994:
1.104 matthew 1995: =cut
1.11 www 1996:
1.104 matthew 1997: ##################################################
1998: ##################################################
1999: sub parmval {
1.119 matthew 2000: my ($what,$sheet)=@_;
2001: my $symb = $sheet->{'usymb'};
1.104 matthew 2002: unless ($symb) { return ''; }
2003: #
1.119 matthew 2004: my $cid = $sheet->{'cid'};
2005: my $csec = $sheet->{'csec'};
2006: my $uname = $sheet->{'uname'};
2007: my $udom = $sheet->{'udom'};
1.104 matthew 2008: my $result='';
2009: #
2010: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
2011: # Cascading lookup scheme
2012: my $rwhat=$what;
2013: $what =~ s/^parameter\_//;
2014: $what =~ s/\_([^\_]+)$/\.$1/;
2015: #
2016: my $symbparm = $symb.'.'.$what;
2017: my $mapparm = $mapname.'___(all).'.$what;
2018: my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
2019: #
2020: my $seclevel = $usercourseprefix.'.['.$csec.'].'.$what;
2021: my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
2022: my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
2023: #
2024: my $courselevel = $usercourseprefix.'.'.$what;
2025: my $courselevelr = $usercourseprefix.'.'.$symbparm;
2026: my $courselevelm = $usercourseprefix.'.'.$mapparm;
2027: # fourth, check user
1.115 albertel 2028: if (defined($uname)) {
2029: return $useropt{$courselevelr} if (defined($useropt{$courselevelr}));
2030: return $useropt{$courselevelm} if (defined($useropt{$courselevelm}));
2031: return $useropt{$courselevel} if (defined($useropt{$courselevel}));
1.104 matthew 2032: }
2033: # third, check course
1.115 albertel 2034: if (defined($csec)) {
2035: return $courseopt{$seclevelr} if (defined($courseopt{$seclevelr}));
2036: return $courseopt{$seclevelm} if (defined($courseopt{$seclevelm}));
2037: return $courseopt{$seclevel} if (defined($courseopt{$seclevel}));
1.104 matthew 2038: }
2039: #
1.115 albertel 2040: return $courseopt{$courselevelr} if (defined($courseopt{$courselevelr}));
2041: return $courseopt{$courselevelm} if (defined($courseopt{$courselevelm}));
2042: return $courseopt{$courselevel} if (defined($courseopt{$courselevel}));
1.104 matthew 2043: # second, check map parms
2044: my $thisparm = $parmhash{$symbparm};
1.115 albertel 2045: return $thisparm if (defined($thisparm));
1.104 matthew 2046: # first, check default
2047: return &Apache::lonnet::metadata($fn,$rwhat.'.default');
1.11 www 2048: }
2049:
1.133 matthew 2050:
2051: ##################################################################
2052: ## Row label formatting routines ##
2053: ##################################################################
2054: sub format_html_rowlabel {
1.149 matthew 2055: my $sheet = shift;
1.133 matthew 2056: my $rowlabel = shift;
2057: return '' if ($rowlabel eq '');
2058: my ($type,$labeldata) = split(':',$rowlabel,2);
2059: my $result = '';
2060: if ($type eq 'symb') {
1.149 matthew 2061: my ($symb,$mapid,$resid,$title) = split(':',$labeldata);
1.133 matthew 2062: $symb = &Apache::lonnet::unescape($symb);
2063: $result = '<a href="/adm/assesscalc?usymb='.$symb.
1.149 matthew 2064: '&uname='.$sheet->{'uname'}.'&udom='.$sheet->{'udom'}.
1.139 matthew 2065: '&mapid='.$mapid.'&resid='.$resid.'">'.$title.'</a>';
1.133 matthew 2066: } elsif ($type eq 'student') {
2067: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
1.148 matthew 2068: if ($fullname =~ /^\s*$/) {
2069: $fullname = $sname.'@'.$sdom;
2070: }
1.133 matthew 2071: $result ='<a href="/adm/studentcalc?uname='.$sname.
2072: '&udom='.$sdom.'">';
2073: $result.=$section.' '.$id." ".$fullname.'</a>';
2074: } elsif ($type eq 'parameter') {
2075: $result = $labeldata;
2076: } else {
2077: $result = '<b><font size=+1>'.$rowlabel.'</font></b>';
2078: }
2079: return $result;
2080: }
2081:
2082: sub format_csv_rowlabel {
1.149 matthew 2083: my $sheet = shift;
1.133 matthew 2084: my $rowlabel = shift;
2085: return '' if ($rowlabel eq '');
2086: my ($type,$labeldata) = split(':',$rowlabel,2);
2087: my $result = '';
2088: if ($type eq 'symb') {
1.149 matthew 2089: my ($symb,$mapid,$resid,$title) = split(':',$labeldata);
1.133 matthew 2090: $symb = &Apache::lonnet::unescape($symb);
2091: $result = $title;
2092: } elsif ($type eq 'student') {
2093: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2094: $result = join('","',($sname,$sdom,$fullname,$section,$id));
2095: } elsif ($type eq 'parameter') {
2096: $labeldata =~ s/<br>/ /g;
2097: $result = $labeldata;
2098: } else {
2099: $result = $rowlabel;
2100: }
2101: return '"'.$result.'"';
2102: }
2103:
1.134 matthew 2104: sub format_excel_rowlabel {
1.149 matthew 2105: my $sheet = shift;
1.125 matthew 2106: my $rowlabel = shift;
1.132 matthew 2107: return '' if ($rowlabel eq '');
1.125 matthew 2108: my ($type,$labeldata) = split(':',$rowlabel,2);
2109: my $result = '';
2110: if ($type eq 'symb') {
1.149 matthew 2111: my ($symb,$mapid,$resid,$title) = split(':',$labeldata);
1.125 matthew 2112: $symb = &Apache::lonnet::unescape($symb);
1.133 matthew 2113: $result = $title;
1.125 matthew 2114: } elsif ($type eq 'student') {
2115: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
1.134 matthew 2116: $section = '' if (! defined($section));
2117: $id = '' if (! defined($id));
2118: my @Data = ($sname,$sdom,$fullname,$section,$id);
2119: $result = \@Data;
1.125 matthew 2120: } elsif ($type eq 'parameter') {
1.133 matthew 2121: $labeldata =~ s/<br>/ /g;
1.127 matthew 2122: $result = $labeldata;
1.125 matthew 2123: } else {
1.133 matthew 2124: $result = $rowlabel;
1.125 matthew 2125: }
2126: return $result;
2127: }
2128:
1.23 www 2129: # ---------------------------------------------- Update rows for course listing
1.28 www 2130: sub updateclasssheet {
1.119 matthew 2131: my ($sheet) = @_;
2132: my $cnum =$sheet->{'cnum'};
2133: my $cdom =$sheet->{'cdom'};
2134: my $cid =$sheet->{'cid'};
2135: my $chome =$sheet->{'chome'};
1.102 matthew 2136: #
1.113 matthew 2137: %Section = ();
2138: #
1.102 matthew 2139: # Read class list and row labels
1.118 matthew 2140: my $classlist = &Apache::loncoursedata::get_classlist();
2141: if (! defined($classlist)) {
2142: return 'Could not access course classlist';
2143: }
1.102 matthew 2144: #
1.23 www 2145: my %currentlist=();
1.118 matthew 2146: foreach my $student (keys(%$classlist)) {
2147: my ($studentDomain,$studentName,$end,$start,$id,$studentSection,
2148: $fullname,$status) = @{$classlist->{$student}};
1.139 matthew 2149: $Section{$studentName.':'.$studentDomain} = $studentSection;
1.118 matthew 2150: if ($ENV{'form.Status'} eq $status || $ENV{'form.Status'} eq 'Any') {
1.125 matthew 2151: $currentlist{$student}=join(':',('student',$studentName,
2152: $studentDomain,$fullname,
2153: $studentSection,$id));
1.118 matthew 2154: }
2155: }
1.102 matthew 2156: #
2157: # Find discrepancies between the course row table and this
2158: #
1.119 matthew 2159: my %f=&getformulas($sheet);
1.102 matthew 2160: my $changed=0;
2161: #
1.119 matthew 2162: $sheet->{'maxrow'}=0;
1.102 matthew 2163: my %existing=();
2164: #
2165: # Now obsolete rows
2166: foreach (keys(%f)) {
2167: if ($_=~/^A(\d+)/) {
1.119 matthew 2168: if ($1 > $sheet->{'maxrow'}) {
2169: $sheet->{'maxrow'}= $1;
2170: }
1.102 matthew 2171: $existing{$f{$_}}=1;
2172: unless ((defined($currentlist{$f{$_}})) || (!$1) ||
1.120 matthew 2173: ($f{$_}=~/^(~~~|---)/)) {
1.102 matthew 2174: $f{$_}='!!! Obsolete';
2175: $changed=1;
1.23 www 2176: }
1.78 matthew 2177: }
1.102 matthew 2178: }
2179: #
2180: # New and unknown keys
1.128 matthew 2181: foreach my $student (sort keys(%currentlist)) {
2182: unless ($existing{$student}) {
1.102 matthew 2183: $changed=1;
1.119 matthew 2184: $sheet->{'maxrow'}++;
1.128 matthew 2185: $f{'A'.$sheet->{'maxrow'}}=$student;
1.78 matthew 2186: }
1.23 www 2187: }
1.119 matthew 2188: if ($changed) {
1.124 matthew 2189: $sheet->{'f'} = \%f;
2190: &setformulas($sheet,%f);
1.119 matthew 2191: }
1.102 matthew 2192: #
1.125 matthew 2193: &setrowlabels($sheet,\%currentlist);
1.23 www 2194: }
1.5 www 2195:
1.28 www 2196: # ----------------------------------- Update rows for student and assess sheets
1.136 matthew 2197: sub get_student_rowlabels {
2198: my ($sheet) = @_;
2199: #
2200: my %course_db;
2201: #
2202: my $stype = $sheet->{'sheettype'};
2203: my $uname = $sheet->{'uname'};
2204: my $udom = $sheet->{'udom'};
2205: #
2206: $sheet->{'rowlabel'} = {};
2207: #
2208: my $identifier =$sheet->{'coursefilename'}.'_'.$stype;
2209: if ($rowlabel_cache{$identifier}) {
2210: %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
2211: } else {
2212: # Get the data and store it in the cache
2213: # Tie hash
2214: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
2215: &GDBM_READER(),0640);
2216: if (! tied(%course_db)) {
2217: return 'Could not access course data';
2218: }
2219: #
2220: my %assesslist;
2221: foreach ('Feedback','Evaluation','Tutoring','Discussion') {
2222: my $symb = '_'.lc($_);
1.149 matthew 2223: $assesslist{$symb} = join(':',('symb',$symb,0,0,$_));
1.136 matthew 2224: }
2225: #
2226: while (my ($key,$srcf) = each(%course_db)) {
2227: next if ($key !~ /^src_(\d+)\.(\d+)$/);
2228: my $mapid = $1;
2229: my $resid = $2;
2230: my $id = $mapid.'.'.$resid;
2231: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
2232: my $symb=
2233: &Apache::lonnet::declutter($course_db{'map_id_'.$mapid}).
2234: '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
2235: $assesslist{$symb}='symb:'.&Apache::lonnet::escape($symb).':'
1.149 matthew 2236: .$mapid.':'.$resid.':'.$course_db{'title_'.$id};
1.136 matthew 2237: }
2238: }
2239: untie(%course_db);
2240: # Store away the data
2241: $sheet->{'rowlabel'} = \%assesslist;
2242: $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
2243: }
2244:
2245: }
2246:
2247: sub get_assess_rowlabels {
1.119 matthew 2248: my ($sheet) = @_;
1.128 matthew 2249: #
1.136 matthew 2250: my %course_db;
1.128 matthew 2251: #
2252: my $stype = $sheet->{'sheettype'};
2253: my $uname = $sheet->{'uname'};
2254: my $udom = $sheet->{'udom'};
1.136 matthew 2255: my $usymb = $sheet->{'usymb'};
2256: #
1.119 matthew 2257: $sheet->{'rowlabel'} = {};
1.136 matthew 2258: my $identifier =$sheet->{'coursefilename'}.'_'.$stype.'_'.$usymb;
2259: #
2260: if ($rowlabel_cache{$identifier}) {
2261: %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
1.104 matthew 2262: } else {
1.136 matthew 2263: # Get the data and store it in the cache
1.104 matthew 2264: # Tie hash
1.136 matthew 2265: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
1.104 matthew 2266: &GDBM_READER(),0640);
1.136 matthew 2267: if (! tied(%course_db)) {
1.104 matthew 2268: return 'Could not access course data';
2269: }
1.125 matthew 2270: #
1.128 matthew 2271: my %parameter_labels=
2272: ('timestamp' =>
2273: 'parameter:Timestamp of Last Transaction<br>timestamp',
2274: 'subnumber' =>
2275: 'parameter:Number of Submissions<br>subnumber',
2276: 'tutornumber' =>
2277: 'parameter:Number of Tutor Responses<br>tutornumber',
2278: 'totalpoints' =>
2279: 'parameter:Total Points Granted<br>totalpoints');
1.136 matthew 2280: while (my ($key,$srcf) = each(%course_db)) {
2281: next if ($key !~ /^src_(\d+)\.(\d+)$/);
2282: my $mapid = $1;
2283: my $resid = $2;
2284: my $id = $mapid.'.'.$resid;
1.104 matthew 2285: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
1.136 matthew 2286: # Loop through the metadata for this key
2287: my @Metadata = split(/,/,
2288: &Apache::lonnet::metadata($srcf,'keys'));
2289: foreach my $key (@Metadata) {
1.104 matthew 2290: next if ($key !~ /^(stores|parameter)_/);
2291: my $display=
2292: &Apache::lonnet::metadata($srcf,$key.'.display');
2293: unless ($display) {
2294: $display.=
2295: &Apache::lonnet::metadata($srcf,$key.'.name');
2296: }
2297: $display.='<br>'.$key;
1.128 matthew 2298: $parameter_labels{$key}='parameter:'.$display;
1.104 matthew 2299: } # end of foreach
2300: }
1.136 matthew 2301: }
2302: untie(%course_db);
2303: # Store away the results
2304: $sheet->{'rowlabel'} = \%parameter_labels;
2305: $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
2306: }
2307:
2308: }
2309:
2310: sub updatestudentassesssheet {
2311: my $sheet = shift;
2312: if ($sheet->{'sheettype'} eq 'studentcalc') {
2313: &get_student_rowlabels($sheet);
2314: } else {
2315: &get_assess_rowlabels($sheet);
1.35 www 2316: }
1.136 matthew 2317: # Determine if any of the information has changed
1.119 matthew 2318: my %f=&getformulas($sheet);
1.104 matthew 2319: my $changed=0;
2320:
1.119 matthew 2321: $sheet->{'maxrow'} = 0;
1.104 matthew 2322: my %existing=();
2323: # Now obsolete rows
1.147 matthew 2324: foreach my $cell (keys(%f)) {
2325: my $formula = $f{$cell};
1.136 matthew 2326: next if ($cell !~ /^A(\d+)/);
2327: $sheet->{'maxrow'} = $1 if ($1 > $sheet->{'maxrow'});
2328: my ($usy,$ufn)=split(/__&&&\__/,$formula);
1.104 matthew 2329: $existing{$usy}=1;
1.119 matthew 2330: unless ((exists($sheet->{'rowlabel'}->{$usy}) &&
2331: (defined($sheet->{'rowlabel'}->{$usy})) || (!$1) ||
1.136 matthew 2332: ($formula =~ /^(~~~|---)/) )) {
1.104 matthew 2333: $f{$_}='!!! Obsolete';
2334: $changed=1;
2335: } elsif ($ufn) {
1.136 matthew 2336: # I do not think this works any more
1.119 matthew 2337: $sheet->{'rowlabel'}->{$usy}
1.136 matthew 2338: =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn&\usymb\=/;
1.104 matthew 2339: }
1.35 www 2340: }
1.104 matthew 2341: # New and unknown keys
1.119 matthew 2342: foreach (keys(%{$sheet->{'rowlabel'}})) {
1.104 matthew 2343: unless ($existing{$_}) {
2344: $changed=1;
1.119 matthew 2345: $sheet->{'maxrow'}++;
2346: $f{'A'.$sheet->{'maxrow'}}=$_;
1.78 matthew 2347: }
1.104 matthew 2348: }
1.119 matthew 2349: if ($changed) {
1.124 matthew 2350: $sheet->{'f'} = \%f;
2351: &setformulas($sheet);
1.119 matthew 2352: }
1.5 www 2353: }
1.3 www 2354:
1.24 www 2355: # ------------------------------------------------ Load data for one assessment
1.16 www 2356:
1.135 matthew 2357: sub loadstudent{
1.140 matthew 2358: my ($sheet,$r,$c)=@_;
2359: my %constants=();
2360: my %formulas=&getformulas($sheet);
1.119 matthew 2361: $cachedassess=$sheet->{'uname'}.':'.$sheet->{'udom'};
1.102 matthew 2362: # Get ALL the student preformance data
1.119 matthew 2363: my @tmp = &Apache::lonnet::dump($sheet->{'cid'},
2364: $sheet->{'udom'},
2365: $sheet->{'uname'},
1.102 matthew 2366: undef);
2367: if ($tmp[0] !~ /^error:/) {
2368: %cachedstores = @tmp;
1.39 www 2369: }
1.102 matthew 2370: undef @tmp;
2371: #
1.36 www 2372: my @assessdata=();
1.145 matthew 2373: foreach my $cell (keys(%formulas)) {
2374: my $value = $formulas{$cell};
1.140 matthew 2375: if(defined($c) && ($c->aborted())) {
2376: last;
2377: }
1.136 matthew 2378: next if ($cell !~ /^A(\d+)/);
1.104 matthew 2379: my $row=$1;
1.136 matthew 2380: next if (($value =~ /^[!~-]/) || ($row==0));
2381: my ($usy,$ufn)=split(/__&&&\__/,$value);
1.128 matthew 2382: @assessdata=&exportsheet($sheet,$sheet->{'uname'},
1.119 matthew 2383: $sheet->{'udom'},
1.140 matthew 2384: 'assesscalc',$usy,$ufn,$r);
1.104 matthew 2385: my $index=0;
1.145 matthew 2386: foreach my $col ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2387: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.136 matthew 2388: if (defined($assessdata[$index])) {
1.104 matthew 2389: if ($assessdata[$index]=~/\D/) {
1.140 matthew 2390: $constants{$col.$row}="'".$assessdata[$index]."'";
1.104 matthew 2391: } else {
1.140 matthew 2392: $constants{$col.$row}=$assessdata[$index];
1.104 matthew 2393: }
1.145 matthew 2394: $formulas{$col.$row}='import' if ($col ne 'A');
1.104 matthew 2395: }
2396: $index++;
1.16 www 2397: }
1.78 matthew 2398: }
1.39 www 2399: $cachedassess='';
2400: undef %cachedstores;
1.140 matthew 2401: $sheet->{'f'} = \%formulas;
1.124 matthew 2402: &setformulas($sheet);
1.140 matthew 2403: &setconstants($sheet,\%constants);
1.16 www 2404: }
2405:
1.24 www 2406: # --------------------------------------------------- Load data for one student
1.109 matthew 2407: #
1.30 www 2408: sub loadcourse {
1.140 matthew 2409: my ($sheet,$r,$c)=@_;
1.135 matthew 2410: #
1.140 matthew 2411: my %constants=();
2412: my %formulas=&getformulas($sheet);
1.135 matthew 2413: #
1.37 www 2414: my $total=0;
1.140 matthew 2415: foreach (keys(%formulas)) {
1.37 www 2416: if ($_=~/^A(\d+)/) {
1.140 matthew 2417: unless ($formulas{$_}=~/^[\!\~\-]/) { $total++; }
1.37 www 2418: }
1.78 matthew 2419: }
1.37 www 2420: my $now=0;
2421: my $since=time;
1.39 www 2422: $r->print(<<ENDPOP);
2423: <script>
2424: popwin=open('','popwin','width=400,height=100');
2425: popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
1.50 www 2426: '<h3>Spreadsheet Calculation Progress</h3>'+
1.39 www 2427: '<form name=popremain>'+
2428: '<input type=text size=35 name=remaining value=Starting></form>'+
2429: '</body></html>');
1.42 www 2430: popwin.document.close();
1.39 www 2431: </script>
2432: ENDPOP
1.37 www 2433: $r->rflush();
1.140 matthew 2434: foreach (keys(%formulas)) {
2435: if(defined($c) && ($c->aborted())) {
2436: last;
2437: }
1.104 matthew 2438: next if ($_!~/^A(\d+)/);
2439: my $row=$1;
1.140 matthew 2440: next if (($formulas{$_}=~/^[\!\~\-]/) || ($row==0));
2441: my ($sname,$sdom) = split(':',$formulas{$_});
2442: my @studentdata=&exportsheet($sheet,$sname,$sdom,'studentcalc',
2443: undef,undef,$r);
1.104 matthew 2444: undef %userrdatas;
2445: $now++;
2446: $r->print('<script>popwin.document.popremain.remaining.value="'.
1.37 www 2447: $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
1.104 matthew 2448: ' secs remaining";</script>');
2449: $r->rflush();
2450: #
2451: my $index=0;
2452: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2453: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.132 matthew 2454: if (defined($studentdata[$index])) {
1.104 matthew 2455: my $col=$_;
2456: if ($studentdata[$index]=~/\D/) {
1.140 matthew 2457: $constants{$col.$row}="'".$studentdata[$index]."'";
1.104 matthew 2458: } else {
1.140 matthew 2459: $constants{$col.$row}=$studentdata[$index];
1.104 matthew 2460: }
2461: unless ($col eq 'A') {
1.140 matthew 2462: $formulas{$col.$row}='import';
1.104 matthew 2463: }
1.132 matthew 2464: }
2465: $index++;
1.24 www 2466: }
1.78 matthew 2467: }
1.140 matthew 2468: $sheet->{'f'}=\%formulas;
1.124 matthew 2469: &setformulas($sheet);
1.140 matthew 2470: &setconstants($sheet,\%constants);
1.43 www 2471: $r->print('<script>popwin.close()</script>');
1.37 www 2472: $r->rflush();
1.24 www 2473: }
2474:
1.6 www 2475: # ------------------------------------------------ Load data for one assessment
1.109 matthew 2476: #
1.29 www 2477: sub loadassessment {
1.140 matthew 2478: my ($sheet,$r,$c)=@_;
1.29 www 2479:
1.119 matthew 2480: my $uhome = $sheet->{'uhome'};
2481: my $uname = $sheet->{'uname'};
2482: my $udom = $sheet->{'udom'};
2483: my $symb = $sheet->{'usymb'};
2484: my $cid = $sheet->{'cid'};
2485: my $cnum = $sheet->{'cnum'};
2486: my $cdom = $sheet->{'cdom'};
2487: my $chome = $sheet->{'chome'};
1.29 www 2488:
1.6 www 2489: my $namespace;
1.29 www 2490: unless ($namespace=$cid) { return ''; }
1.104 matthew 2491: # Get stored values
2492: my %returnhash=();
2493: if ($cachedassess eq $uname.':'.$udom) {
2494: #
2495: # get data out of the dumped stores
2496: #
2497: my $version=$cachedstores{'version:'.$symb};
2498: my $scope;
2499: for ($scope=1;$scope<=$version;$scope++) {
2500: foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
2501: $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
2502: }
2503: }
2504: } else {
2505: #
2506: # restore individual
2507: #
1.109 matthew 2508: %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
2509: for (my $version=1;$version<=$returnhash{'version'};$version++) {
1.104 matthew 2510: foreach (split(/\:/,$returnhash{$version.':keys'})) {
2511: $returnhash{$_}=$returnhash{$version.':'.$_};
2512: }
2513: }
1.6 www 2514: }
1.109 matthew 2515: #
1.104 matthew 2516: # returnhash now has all stores for this resource
2517: # convert all "_" to "." to be able to use libraries, multiparts, etc
1.109 matthew 2518: #
2519: # This is dumb. It is also necessary :(
1.76 www 2520: my @oldkeys=keys %returnhash;
1.109 matthew 2521: #
1.116 matthew 2522: foreach my $name (@oldkeys) {
2523: my $value=$returnhash{$name};
2524: delete $returnhash{$name};
1.76 www 2525: $name=~s/\_/\./g;
2526: $returnhash{$name}=$value;
1.78 matthew 2527: }
1.104 matthew 2528: # initialize coursedata and userdata for this user
1.31 www 2529: undef %courseopt;
2530: undef %useropt;
1.29 www 2531:
2532: my $userprefix=$uname.'_'.$udom.'_';
1.116 matthew 2533:
1.11 www 2534: unless ($uhome eq 'no_host') {
1.104 matthew 2535: # Get coursedata
1.105 matthew 2536: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
1.116 matthew 2537: my %Tmp = &Apache::lonnet::dump('resourcedata',$cdom,$cnum);
2538: $courserdatas{$cid}=\%Tmp;
2539: $courserdatas{$cid.'.last_cache'}=time;
1.105 matthew 2540: }
1.116 matthew 2541: while (my ($name,$value) = each(%{$courserdatas{$cid}})) {
2542: $courseopt{$userprefix.$name}=$value;
1.104 matthew 2543: }
2544: # Get userdata (if present)
1.116 matthew 2545: unless ((time-$userrdatas{$uname.'@'.$udom.'.last_cache'})<240) {
2546: my %Tmp = &Apache::lonnet::dump('resourcedata',$udom,$uname);
2547: $userrdatas{$cid} = \%Tmp;
1.114 matthew 2548: # Most of the time the user does not have a 'resourcedata.db'
2549: # file. We need to cache that we got nothing instead of bothering
2550: # with requesting it every time.
1.116 matthew 2551: $userrdatas{$uname.'@'.$udom.'.last_cache'}=time;
1.109 matthew 2552: }
1.116 matthew 2553: while (my ($name,$value) = each(%{$userrdatas{$cid}})) {
2554: $useropt{$userprefix.$name}=$value;
1.104 matthew 2555: }
1.29 www 2556: }
1.104 matthew 2557: # now courseopt, useropt initialized for this user and course
2558: # (used by parmval)
2559: #
2560: # Load keys for this assessment only
2561: #
1.60 www 2562: my %thisassess=();
2563: my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
1.78 matthew 2564: foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
1.60 www 2565: $thisassess{$_}=1;
1.78 matthew 2566: }
1.104 matthew 2567: #
2568: # Load parameters
2569: #
2570: my %c=();
2571: if (tie(%parmhash,'GDBM_File',
1.119 matthew 2572: $sheet->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
2573: my %f=&getformulas($sheet);
1.125 matthew 2574: foreach my $cell (keys(%f)) {
2575: next if ($cell !~ /^A/);
2576: next if ($f{$cell} =~/^[\!\~\-]/);
2577: if ($f{$cell}=~/^parameter/) {
2578: if (defined($thisassess{$f{$cell}})) {
2579: my $val = &parmval($f{$cell},$sheet);
2580: $c{$cell} = $val;
2581: $c{$f{$cell}} = $val;
1.104 matthew 2582: }
2583: } else {
1.125 matthew 2584: my $key=$f{$cell};
1.104 matthew 2585: my $ckey=$key;
2586: $key=~s/^stores\_/resource\./;
2587: $key=~s/\_/\./g;
1.125 matthew 2588: $c{$cell}=$returnhash{$key};
1.104 matthew 2589: $c{$ckey}=$returnhash{$key};
2590: }
1.6 www 2591: }
1.104 matthew 2592: untie(%parmhash);
1.78 matthew 2593: }
1.122 matthew 2594: &setconstants($sheet,\%c);
1.6 www 2595: }
2596:
1.10 www 2597: # --------------------------------------------------------- Various form fields
2598:
2599: sub textfield {
2600: my ($title,$name,$value)=@_;
2601: return "\n<p><b>$title:</b><br>".
1.104 matthew 2602: '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
1.10 www 2603: }
2604:
2605: sub hiddenfield {
2606: my ($name,$value)=@_;
2607: return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
2608: }
2609:
2610: sub selectbox {
2611: my ($title,$name,$value,%options)=@_;
2612: my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
1.78 matthew 2613: foreach (sort keys(%options)) {
1.10 www 2614: $selout.='<option value="'.$_.'"';
2615: if ($_ eq $value) { $selout.=' selected'; }
2616: $selout.='>'.$options{$_}.'</option>';
1.78 matthew 2617: }
1.10 www 2618: return $selout.'</select>';
2619: }
2620:
1.28 www 2621: # =============================================== Update information in a sheet
2622: #
2623: # Add new users or assessments, etc.
2624: #
2625:
2626: sub updatesheet {
1.119 matthew 2627: my ($sheet)=@_;
1.136 matthew 2628: if ($sheet->{'sheettype'} eq 'classcalc') {
1.119 matthew 2629: return &updateclasssheet($sheet);
1.28 www 2630: } else {
1.119 matthew 2631: return &updatestudentassesssheet($sheet);
1.28 www 2632: }
2633: }
2634:
2635: # =================================================== Load the rows for a sheet
2636: #
2637: # Import the data for rows
2638: #
2639:
1.37 www 2640: sub loadrows {
1.119 matthew 2641: my ($sheet,$r)=@_;
1.140 matthew 2642: my $c = $r->connection;
1.119 matthew 2643: my $stype=$sheet->{'sheettype'};
1.28 www 2644: if ($stype eq 'classcalc') {
1.140 matthew 2645: &loadcourse($sheet,$r,$c);
1.28 www 2646: } elsif ($stype eq 'studentcalc') {
1.140 matthew 2647: &loadstudent($sheet,$r,$c);
1.28 www 2648: } else {
1.140 matthew 2649: &loadassessment($sheet,$r,$c);
1.28 www 2650: }
2651: }
2652:
1.47 www 2653: # ======================================================= Forced recalculation?
2654:
2655: sub checkthis {
2656: my ($keyname,$time)=@_;
1.144 matthew 2657: if (! exists($expiredates{$keyname})) {
2658: return 0;
2659: } else {
2660: return ($time<$expiredates{$keyname});
2661: }
1.47 www 2662: }
1.104 matthew 2663:
1.47 www 2664: sub forcedrecalc {
2665: my ($uname,$udom,$stype,$usymb)=@_;
2666: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2667: my $time=$oldsheets{$key.'.time'};
1.53 www 2668: if ($ENV{'form.forcerecalc'}) { return 1; }
1.47 www 2669: unless ($time) { return 1; }
2670: if ($stype eq 'assesscalc') {
1.120 matthew 2671: my $map=(split(/___/,$usymb))[0];
1.47 www 2672: if (&checkthis('::assesscalc:',$time) ||
2673: &checkthis('::assesscalc:'.$map,$time) ||
2674: &checkthis('::assesscalc:'.$usymb,$time) ||
1.49 www 2675: &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
2676: &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
2677: &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
1.47 www 2678: return 1;
2679: }
2680: } else {
2681: if (&checkthis('::studentcalc:',$time) ||
1.51 www 2682: &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
1.47 www 2683: return 1;
2684: }
2685: }
2686: return 0;
2687: }
2688:
1.28 www 2689: # ============================================================== Export handler
1.128 matthew 2690: # exportsheet
2691: # returns the export row for a spreadsheet.
2692: #
1.28 www 2693: sub exportsheet {
1.140 matthew 2694: my ($sheet,$uname,$udom,$stype,$usymb,$fn,$r)=@_;
1.145 matthew 2695: my $flag = 0;
1.128 matthew 2696: $uname = $uname || $sheet->{'uname'};
2697: $udom = $udom || $sheet->{'udom'};
2698: $stype = $stype || $sheet->{'sheettype'};
1.104 matthew 2699: my @exportarr=();
1.132 matthew 2700: if (defined($usymb) && ($usymb=~/^\_(\w+)/) &&
2701: (!defined($fn) || $fn eq '')) {
1.104 matthew 2702: $fn='default_'.$1;
2703: }
2704: #
2705: # Check if cached
2706: #
2707: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2708: my $found='';
2709: if ($oldsheets{$key}) {
1.120 matthew 2710: foreach (split(/___&\___/,$oldsheets{$key})) {
2711: my ($name,$value)=split(/___=___/,$_);
1.46 www 2712: if ($name eq $fn) {
1.104 matthew 2713: $found=$value;
1.46 www 2714: }
1.104 matthew 2715: }
1.46 www 2716: }
1.104 matthew 2717: unless ($found) {
1.128 matthew 2718: &cachedssheets($sheet,$uname,$udom);
1.104 matthew 2719: if ($oldsheets{$key}) {
1.120 matthew 2720: foreach (split(/___&\___/,$oldsheets{$key})) {
2721: my ($name,$value)=split(/___=___/,$_);
1.104 matthew 2722: if ($name eq $fn) {
2723: $found=$value;
2724: }
2725: }
2726: }
1.44 www 2727: }
1.104 matthew 2728: #
2729: # Check if still valid
2730: #
2731: if ($found) {
2732: if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
2733: $found='';
2734: }
2735: }
2736: if ($found) {
2737: #
2738: # Return what was cached
2739: #
1.120 matthew 2740: @exportarr=split(/___;___/,$found);
2741: return @exportarr;
2742: }
2743: #
2744: # Not cached
1.135 matthew 2745: #
1.128 matthew 2746: my ($newsheet)=&makenewsheet($uname,$udom,$stype,$usymb);
2747: &readsheet($newsheet,$fn);
2748: &updatesheet($newsheet);
1.140 matthew 2749: &loadrows($newsheet,$r);
1.128 matthew 2750: &calcsheet($newsheet);
2751: @exportarr=&exportdata($newsheet);
1.131 matthew 2752: ##
2753: ## Store now
2754: ##
1.120 matthew 2755: #
1.131 matthew 2756: # load in the old value
1.120 matthew 2757: #
1.131 matthew 2758: my %currentlystored=();
1.120 matthew 2759: if ($stype eq 'studentcalc') {
1.131 matthew 2760: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets',
2761: [$key],
2762: $sheet->{'cdom'},$sheet->{'cnum'});
2763: if ($tmp[0]!~/^error/) {
1.145 matthew 2764: # We only got one key, so we will access it directly.
2765: foreach (split('___&___',$tmp[1])) {
2766: my ($key,$value) = split('___=___',$_);
2767: $key = '' if (! defined($key));
2768: $currentlystored{$key} = $value;
2769: }
1.131 matthew 2770: }
2771: } else {
2772: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets_'.
2773: $sheet->{'cid'},[$key],
2774: $sheet->{'udom'},$sheet->{'uname'});
2775: if ($tmp[0]!~/^error/) {
1.145 matthew 2776: # We only got one key, so we will access it directly.
2777: foreach (split('___&___',$tmp[1])) {
2778: my ($key,$value) = split('___=___',$_);
2779: $key = '' if (! defined($key));
2780: $currentlystored{$key} = $value;
2781: }
1.120 matthew 2782: }
2783: }
1.131 matthew 2784: #
2785: # Add the new line
2786: #
1.120 matthew 2787: $currentlystored{$fn}=join('___;___',@exportarr);
2788: #
1.131 matthew 2789: # Stick everything back together
2790: #
1.120 matthew 2791: my $newstore='';
2792: foreach (keys(%currentlystored)) {
2793: if ($newstore) { $newstore.='___&___'; }
2794: $newstore.=$_.'___=___'.$currentlystored{$_};
2795: }
2796: my $now=time;
1.131 matthew 2797: #
2798: # Store away the new value
2799: #
1.144 matthew 2800: my $timekey = $key.'.time';
1.120 matthew 2801: if ($stype eq 'studentcalc') {
1.144 matthew 2802: my $result = &Apache::lonnet::put('nohist_calculatedsheets',
2803: { $key => $newstore,
2804: $timekey => $now },
2805: $sheet->{'cdom'},
2806: $sheet->{'cnum'});
2807: } else {
2808: my $result = &Apache::lonnet::put('nohist_calculatedsheets_'.$sheet->{'cid'},
2809: { $key => $newstore,
2810: $timekey => $now },
2811: $sheet->{'udom'},
2812: $sheet->{'uname'});
1.78 matthew 2813: }
1.104 matthew 2814: return @exportarr;
1.44 www 2815: }
1.104 matthew 2816:
1.48 www 2817: # ============================================================ Expiration Dates
2818: #
2819: # Load previously cached student spreadsheets for this course
2820: #
1.136 matthew 2821: sub load_spreadsheet_expirationdates {
1.48 www 2822: undef %expiredates;
2823: my $cid=$ENV{'request.course.id'};
1.128 matthew 2824: my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
2825: $ENV{'course.'.$cid.'.domain'},
2826: $ENV{'course.'.$cid.'.num'});
1.140 matthew 2827: if (lc($tmp[0]) !~ /^error/){
1.128 matthew 2828: %expiredates = @tmp;
1.48 www 2829: }
2830: }
1.44 www 2831:
2832: # ===================================================== Calculated sheets cache
2833: #
1.46 www 2834: # Load previously cached student spreadsheets for this course
1.44 www 2835: #
2836:
1.46 www 2837: sub cachedcsheets {
1.44 www 2838: my $cid=$ENV{'request.course.id'};
1.128 matthew 2839: my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
2840: $ENV{'course.'.$cid.'.domain'},
2841: $ENV{'course.'.$cid.'.num'});
2842: if ($tmp[0] !~ /^error/) {
2843: my %StupidTempHash = @tmp;
2844: while (my ($key,$value) = each %StupidTempHash) {
2845: $oldsheets{$key} = $value;
1.78 matthew 2846: }
1.44 www 2847: }
1.28 www 2848: }
2849:
1.46 www 2850: # ===================================================== Calculated sheets cache
2851: #
2852: # Load previously cached assessment spreadsheets for this student
2853: #
2854:
2855: sub cachedssheets {
1.128 matthew 2856: my ($sheet,$uname,$udom) = @_;
2857: $uname = $uname || $sheet->{'uname'};
2858: $udom = $udom || $sheet->{'udom'};
1.136 matthew 2859: if (! $loadedcaches{$uname.'_'.$udom}) {
1.128 matthew 2860: my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
2861: $sheet->{'udom'},
2862: $sheet->{'uname'});
2863: if ($tmp[0] !~ /^error/) {
1.136 matthew 2864: my %TempHash = @tmp;
2865: my $count = 0;
2866: while (my ($key,$value) = each %TempHash) {
1.128 matthew 2867: $oldsheets{$key} = $value;
1.136 matthew 2868: $count++;
1.128 matthew 2869: }
2870: $loadedcaches{$sheet->{'uname'}.'_'.$sheet->{'udom'}}=1;
1.78 matthew 2871: }
1.46 www 2872: }
1.136 matthew 2873:
1.46 www 2874: }
2875:
2876: # ===================================================== Calculated sheets cache
2877: #
2878: # Load previously cached assessment spreadsheets for this student
2879: #
2880:
1.12 www 2881: # ================================================================ Main handler
1.28 www 2882: #
2883: # Interactive call to screen
2884: #
2885: #
1.3 www 2886: sub handler {
1.7 www 2887: my $r=shift;
1.110 www 2888:
1.135 matthew 2889: my ($sheettype) = ($r->uri=~/\/(\w+)$/);
2890:
1.118 matthew 2891: if (! exists($ENV{'form.Status'})) {
2892: $ENV{'form.Status'} = 'Active';
2893: }
1.135 matthew 2894: if ( ! exists($ENV{'form.output'}) ||
2895: ($sheettype ne 'classcalc' &&
2896: lc($ENV{'form.output'}) eq 'recursive excel')) {
1.134 matthew 2897: $ENV{'form.output'} = 'HTML';
2898: }
1.136 matthew 2899: #
2900: # Overload checking
2901: #
1.116 matthew 2902: # Check this server
1.111 matthew 2903: my $loaderror=&Apache::lonnet::overloaderror($r);
2904: if ($loaderror) { return $loaderror; }
1.116 matthew 2905: # Check the course homeserver
1.111 matthew 2906: $loaderror= &Apache::lonnet::overloaderror($r,
2907: $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
2908: if ($loaderror) { return $loaderror; }
1.136 matthew 2909: #
2910: # HTML Header
2911: #
1.28 www 2912: if ($r->header_only) {
1.104 matthew 2913: $r->content_type('text/html');
2914: $r->send_http_header;
2915: return OK;
2916: }
1.136 matthew 2917: #
1.104 matthew 2918: # Global directory configs
1.136 matthew 2919: #
1.106 matthew 2920: $includedir = $r->dir_config('lonIncludes');
2921: $tmpdir = $r->dir_config('lonDaemons').'/tmp/';
1.136 matthew 2922: #
2923: # Roles Checking
2924: #
1.104 matthew 2925: # Needs to be in a course
1.106 matthew 2926: if (! $ENV{'request.course.fn'}) {
2927: # Not in a course, or not allowed to modify parms
2928: $ENV{'user.error.msg'}=
2929: $r->uri.":opa:0:0:Cannot modify spreadsheet";
2930: return HTTP_NOT_ACCEPTABLE;
2931: }
1.136 matthew 2932: #
1.106 matthew 2933: # Get query string for limited number of parameters
1.136 matthew 2934: #
1.139 matthew 2935: &Apache::loncommon::get_unprocessed_cgi
2936: ($ENV{'QUERY_STRING'},['uname','udom','usymb','ufn','mapid','resid']);
1.136 matthew 2937: #
2938: # Deal with restricted student permissions
2939: #
1.111 matthew 2940: if ($ENV{'request.role'} =~ /^st\./) {
2941: delete $ENV{'form.unewfield'} if (exists($ENV{'form.unewfield'}));
2942: delete $ENV{'form.unewformula'} if (exists($ENV{'form.unewformula'}));
2943: }
1.136 matthew 2944: #
2945: # Clean up symb and spreadsheet filename
2946: #
1.106 matthew 2947: if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
2948: $ENV{'form.ufn'}='default_'.$1;
2949: }
1.136 matthew 2950: #
1.106 matthew 2951: # Interactive loading of specific sheet?
1.136 matthew 2952: #
1.106 matthew 2953: if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
2954: $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
2955: }
2956: #
2957: # Determine the user name and domain for the sheet.
2958: my $aname;
2959: my $adom;
2960: unless ($ENV{'form.uname'}) {
2961: $aname=$ENV{'user.name'};
2962: $adom=$ENV{'user.domain'};
2963: } else {
2964: $aname=$ENV{'form.uname'};
2965: $adom=$ENV{'form.udom'};
2966: }
2967: #
1.136 matthew 2968: # Open page, try to prevent browser cache.
2969: #
1.106 matthew 2970: $r->content_type('text/html');
2971: $r->header_out('Cache-control','no-cache');
2972: $r->header_out('Pragma','no-cache');
2973: $r->send_http_header;
1.136 matthew 2974: #
2975: # Header....
2976: #
1.106 matthew 2977: $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
1.138 matthew 2978: my $nothing = "''";
2979: if ($ENV{'browser.type'} eq 'explorer') {
2980: $nothing = "'javascript:void(0);'";
2981: }
2982:
1.111 matthew 2983: if ($ENV{'request.role'} !~ /^st\./) {
2984: $r->print(<<ENDSCRIPT);
1.10 www 2985: <script language="JavaScript">
2986:
1.138 matthew 2987: var editwin;
2988:
2989: function celledit(cellname,cellformula) {
2990: var edit_text = '';
2991: edit_text +='<html><head><title>Cell Edit Window</title></head><body>';
2992: edit_text += '<form name="editwinform">';
2993: edit_text += '<center><h3>Cell '+cellname+'</h3>';
2994: edit_text += '<textarea name="newformula" cols="40" rows="6"';
2995: edit_text += ' wrap="off" >'+cellformula+'</textarea>';
2996: edit_text += '</br>';
2997: edit_text += '<input type="button" name="accept" value="Accept"';
2998: edit_text += ' onClick=\\\'javascript:';
2999: edit_text += 'opener.document.sheet.unewfield.value=';
3000: edit_text += '"'+cellname+'";';
3001: edit_text += 'opener.document.sheet.unewformula.value=';
3002: edit_text += 'document.editwinform.newformula.value;';
3003: edit_text += 'opener.document.sheet.submit();';
3004: edit_text += 'self.close()\\\' />';
3005: edit_text += ' ';
3006: edit_text += '<input type="button" name="abort" ';
3007: edit_text += 'value="Discard Changes"';
3008: edit_text += ' onClick="javascript:self.close()" />';
3009: edit_text += '</center></body></html>';
3010:
3011: if (editwin != null && !(editwin.closed) ) {
3012: editwin.close();
1.10 www 3013: }
1.138 matthew 3014:
3015: editwin = window.open($nothing,'CellEditWin','height=200,width=350,scrollbars=no,resizeable=yes,alwaysRaised=yes,dependent=yes',true);
3016: editwin.document.write(edit_text);
1.10 www 3017: }
3018:
1.55 www 3019: function changesheet(cn) {
3020: document.sheet.unewfield.value=cn;
3021: document.sheet.unewformula.value='changesheet';
3022: document.sheet.submit();
3023: }
3024:
1.92 www 3025: function insertrow(cn) {
3026: document.sheet.unewfield.value='insertrow';
3027: document.sheet.unewformula.value=cn;
3028: document.sheet.submit();
3029: }
3030:
1.10 www 3031: </script>
3032: ENDSCRIPT
1.111 matthew 3033: }
1.106 matthew 3034: $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
1.138 matthew 3035: '<form action="'.$r->uri.'" name="sheet" method="post">');
1.106 matthew 3036: $r->print(&hiddenfield('uname',$ENV{'form.uname'}).
3037: &hiddenfield('udom',$ENV{'form.udom'}).
3038: &hiddenfield('usymb',$ENV{'form.usymb'}).
3039: &hiddenfield('unewfield','').
3040: &hiddenfield('unewformula',''));
3041: $r->rflush();
3042: #
3043: # Full recalc?
1.136 matthew 3044: #
1.106 matthew 3045: if ($ENV{'form.forcerecalc'}) {
3046: $r->print('<h4>Completely Recalculating Sheet ...</h4>');
3047: undef %spreadsheets;
3048: undef %courserdatas;
3049: undef %userrdatas;
3050: undef %defaultsheets;
1.136 matthew 3051: undef %rowlabel_cache;
1.106 matthew 3052: }
3053: # Read new sheet or modified worksheet
1.135 matthew 3054: my ($sheet)=&makenewsheet($aname,$adom,$sheettype,$ENV{'form.usymb'});
1.106 matthew 3055: #
1.139 matthew 3056: # Check user permissions
3057: if (($sheet->{'sheettype'} eq 'classcalc' ) ||
3058: ($sheet->{'uname'} ne $ENV{'user.name'} ) ||
3059: ($sheet->{'udom'} ne $ENV{'user.domain'})) {
3060: unless (&Apache::lonnet::allowed('vgr',$sheet->{'cid'})) {
3061: $r->print('<h1>Access Permission Denied</h1>'.
3062: '</form></body></html>');
3063: return OK;
3064: }
3065: }
3066: # Print out user information
3067: $r->print('<h2>'.$sheet->{'coursedesc'}.'</h2>');
3068: if ($sheet->{'sheettype'} ne 'classcalc') {
3069: $r->print('<h2>'.&gettitle($sheet).'</h2><p>');
3070: }
3071: if ($sheet->{'sheettype'} eq 'assesscalc') {
3072: $r->print('<b>User:</b> '.$sheet->{'uname'}.
3073: '<br /><b>Domain:</b> '.$sheet->{'udom'}.'<br />');
3074: }
3075: if ($sheet->{'sheettype'} eq 'studentcalc' ||
3076: $sheet->{'sheettype'} eq 'assesscalc') {
3077: $r->print('<b>Section/Group:</b>'.$sheet->{'csec'}.'</p>');
3078: }
3079: #
1.106 matthew 3080: # If a new formula had been entered, go from work copy
3081: if ($ENV{'form.unewfield'}) {
3082: $r->print('<h2>Modified Workcopy</h2>');
3083: $ENV{'form.unewformula'}=~s/\'/\"/g;
3084: $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
3085: $ENV{'form.unewformula'}.'<p>');
1.119 matthew 3086: $sheet->{'filename'} = $ENV{'form.ufn'};
3087: &tmpread($sheet,$ENV{'form.unewfield'},$ENV{'form.unewformula'});
1.106 matthew 3088: } elsif ($ENV{'form.saveas'}) {
1.119 matthew 3089: $sheet->{'filename'} = $ENV{'form.ufn'};
3090: &tmpread($sheet);
1.106 matthew 3091: } else {
1.119 matthew 3092: &readsheet($sheet,$ENV{'form.ufn'});
1.106 matthew 3093: }
3094: # Additional options
1.119 matthew 3095: if ($sheet->{'sheettype'} eq 'assesscalc') {
1.106 matthew 3096: $r->print('<p><font size=+2>'.
3097: '<a href="/adm/studentcalc?'.
1.119 matthew 3098: 'uname='.$sheet->{'uname'}.
3099: '&udom='.$sheet->{'udom'}.'">'.
1.139 matthew 3100: 'Level up: Student Sheet</a></font></p>');
1.106 matthew 3101: }
1.119 matthew 3102: if (($sheet->{'sheettype'} eq 'studentcalc') &&
3103: (&Apache::lonnet::allowed('vgr',$sheet->{'cid'}))) {
1.106 matthew 3104: $r->print ('<p><font size=+2><a href="/adm/classcalc">'.
1.139 matthew 3105: 'Level up: Course Sheet</a></font></p>');
1.106 matthew 3106: }
1.139 matthew 3107: # Recalc button
3108: $r->print('<br />'.
3109: '<input type="submit" name="forcerecalc" '.
3110: 'value="Completely Recalculate Sheet"></p>');
1.106 matthew 3111: # Save dialog
3112: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3113: my $fname=$ENV{'form.ufn'};
3114: $fname=~s/\_[^\_]+$//;
3115: if ($fname eq 'default') { $fname='course_default'; }
3116: $r->print('<input type=submit name=saveas value="Save as ...">'.
3117: '<input type=text size=20 name=newfn value="'.$fname.'">'.
3118: 'make default: <input type=checkbox name="makedefufn"><p>');
3119: }
1.119 matthew 3120: $r->print(&hiddenfield('ufn',$sheet->{'filename'}));
1.106 matthew 3121: # Load dialog
3122: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3123: $r->print('<p><input type=submit name=load value="Load ...">'.
3124: '<select name="loadthissheet">'.
3125: '<option name="default">Default</option>');
1.119 matthew 3126: foreach (&othersheets($sheet)) {
1.106 matthew 3127: $r->print('<option name="'.$_.'"');
3128: if ($ENV{'form.ufn'} eq $_) {
3129: $r->print(' selected');
1.104 matthew 3130: }
1.106 matthew 3131: $r->print('>'.$_.'</option>');
3132: }
3133: $r->print('</select><p>');
1.119 matthew 3134: if ($sheet->{'sheettype'} eq 'studentcalc') {
1.116 matthew 3135: &setothersheets($sheet,
1.119 matthew 3136: &othersheets($sheet,'assesscalc'));
1.104 matthew 3137: }
1.106 matthew 3138: }
1.136 matthew 3139: #
3140: # Set up caching mechanisms
3141: #
3142: &load_spreadsheet_expirationdates();
3143: # Clear out old caches if we have not seen this class before.
3144: if (exists($oldsheets{'course'}) &&
3145: $oldsheets{'course'} ne $sheet->{'cid'}) {
3146: undef %oldsheets;
3147: undef %loadedcaches;
3148: }
3149: $oldsheets{'course'} = $sheet->{'cid'};
3150: #
1.119 matthew 3151: if ($sheet->{'sheettype'} eq 'classcalc') {
1.106 matthew 3152: $r->print("Loading previously calculated student sheets ...\n");
1.104 matthew 3153: $r->rflush();
1.106 matthew 3154: &cachedcsheets();
1.119 matthew 3155: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1.106 matthew 3156: $r->print("Loading previously calculated assessment sheets ...\n");
1.46 www 3157: $r->rflush();
1.128 matthew 3158: &cachedssheets($sheet);
1.106 matthew 3159: }
3160: # Update sheet, load rows
3161: $r->print("Loaded sheet(s), updating rows ...<br>\n");
3162: $r->rflush();
3163: #
1.119 matthew 3164: &updatesheet($sheet);
1.106 matthew 3165: $r->print("Updated rows, loading row data ...\n");
3166: $r->rflush();
3167: #
1.119 matthew 3168: &loadrows($sheet,$r);
1.106 matthew 3169: $r->print("Loaded row data, calculating sheet ...<br>\n");
3170: $r->rflush();
3171: #
1.116 matthew 3172: my $calcoutput=&calcsheet($sheet);
1.106 matthew 3173: $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
3174: # See if something to save
3175: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3176: my $fname='';
3177: if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
3178: $fname=~s/\W/\_/g;
3179: if ($fname eq 'default') { $fname='course_default'; }
1.119 matthew 3180: $fname.='_'.$sheet->{'sheettype'};
3181: $sheet->{'filename'} = $fname;
1.106 matthew 3182: $ENV{'form.ufn'}=$fname;
3183: $r->print('<p>Saving spreadsheet: '.
1.119 matthew 3184: &writesheet($sheet,$ENV{'form.makedefufn'}).
1.116 matthew 3185: '<p>');
1.104 matthew 3186: }
1.106 matthew 3187: }
3188: #
1.116 matthew 3189: # Write the modified worksheet
1.139 matthew 3190: $r->print('<b>Current sheet:</b> '.$sheet->{'filename'}.'</p>');
1.119 matthew 3191: &tmpwrite($sheet);
1.141 matthew 3192: if ($sheet->{'sheettype'} eq 'assesscalc') {
1.139 matthew 3193: $r->print('<p>Show rows with empty A column: ');
1.62 www 3194: } else {
1.140 matthew 3195: $r->print('<p>Show empty rows: ');
1.120 matthew 3196: }
1.106 matthew 3197: #
1.77 www 3198: $r->print(&hiddenfield('userselhidden','true').
1.106 matthew 3199: '<input type="checkbox" name="showall" onClick="submit()"');
3200: #
1.77 www 3201: if ($ENV{'form.showall'}) {
1.106 matthew 3202: $r->print(' checked');
1.77 www 3203: } else {
1.106 matthew 3204: unless ($ENV{'form.userselhidden'}) {
3205: unless
1.128 matthew 3206: ($ENV{'course.'.$sheet->{'cid'}.'.hideemptyrows'} eq 'yes') {
1.106 matthew 3207: $r->print(' checked');
3208: $ENV{'form.showall'}=1;
3209: }
3210: }
1.77 www 3211: }
1.61 www 3212: $r->print('>');
1.120 matthew 3213: #
3214: # CSV format checkbox (classcalc sheets only)
1.134 matthew 3215: $r->print(' Output as <select name="output" size="1" onClick="submit()">'.
3216: "\n");
1.135 matthew 3217: foreach my $mode (qw/HTML CSV Excel/) {
1.134 matthew 3218: $r->print('<option value="'.$mode.'"');
3219: if ($ENV{'form.output'} eq $mode) {
3220: $r->print(' selected ');
3221: }
3222: $r->print('>'.$mode.'</option>'."\n");
1.135 matthew 3223: }
1.150 ! matthew 3224: #
! 3225: # Mulit-sheet excel takes too long and does not work at all for large
! 3226: # classes. Future inclusion of this option may be possible with the
! 3227: # Spreadsheet::WriteExcel::Big and speed improvements.
! 3228: #
! 3229: # if ($sheet->{'sheettype'} eq 'classcalc') {
! 3230: # $r->print('<option value="recursive excel"');
! 3231: # if ($ENV{'form.output'} eq 'recursive excel') {
! 3232: # $r->print(' selected ');
! 3233: # }
! 3234: # $r->print(">Multi-Sheet Excel</option>\n");
! 3235: # }
1.134 matthew 3236: $r->print("</select>\n");
3237: #
1.119 matthew 3238: if ($sheet->{'sheettype'} eq 'classcalc') {
3239: $r->print(' Student Status: '.
3240: &Apache::lonhtmlcommon::StatusOptions
3241: ($ENV{'form.Status'},'sheet'));
1.69 www 3242: }
1.120 matthew 3243: #
3244: # Buttons to insert rows
1.134 matthew 3245: # $r->print(<<ENDINSERTBUTTONS);
3246: #<br>
3247: #<input type='button' onClick='insertrow("top");'
3248: #value='Insert Row Top'>
3249: #<input type='button' onClick='insertrow("bottom");'
3250: #value='Insert Row Bottom'><br>
3251: #ENDINSERTBUTTONS
1.106 matthew 3252: # Print out sheet
1.143 matthew 3253: &outsheet($sheet,$r);
1.10 www 3254: $r->print('</form></body></html>');
1.106 matthew 3255: # Done
1.3 www 3256: return OK;
1.1 www 3257: }
3258:
3259: 1;
3260: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>