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