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