Annotation of loncom/interface/lonspreadsheet.pm, revision 1.169
1.79 matthew 1: #
1.169 ! matthew 2: # $Id: lonspreadsheet.pm,v 1.168 2003/02/13 19:07:46 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')};
1.168 matthew 1747: # $self->logthis($self->get_errorlog());
1.164 matthew 1748: return $result;
1749: }
1750:
1751: ##
1752: ## sync_safe_space: Called by calcsheet to make sure all the data we
1753: # need to calculate is placed into the safe space
1754: ##
1755: sub sync_safe_space {
1756: my $self = shift;
1757: # Inside the safe space 'formulas' has a diabolical alter-ego named 'f'.
1758: %{$self->{'safe'}->varglob('f')}=%{$self->{'formulas'}};
1759: # 'constants' leads a peaceful hidden life of 'c'.
1760: %{$self->{'safe'}->varglob('c')}=%{$self->{'constants'}};
1761: # 'othersheets' hides as 'os', a disguise few can penetrate.
1762: @{$self->{'safe'}->varglob('os')}=@{$self->{'othersheets'}};
1763: }
1764:
1765: ##
1766: ## Retrieve the error log from the safe space (used for debugging)
1767: ##
1768: sub get_errorlog {
1769: my $self = shift;
1770: $self->{'errorlog'} = ${$self->{'safe'}->varglob('errorlog')};
1771: return $self->{'errorlog'};
1772: }
1773:
1774: ##
1775: ## Clear the error log inside the safe space
1776: ##
1777: sub clear_errorlog {
1778: my $self = shift;
1779: ${$self->{'safe'}->varglob('errorlog')} = '';
1780: $self->{'errorlog'} = '';
1781: }
1782:
1783:
1784: ########################################################
1785: #### Spreadsheet content retrieval/setting methods #####
1786: ########################################################
1787: ##
1.165 matthew 1788: ## constants: either set or get the constants
1789: ##
1.164 matthew 1790: ##
1791: sub constants {
1792: my $self=shift;
1793: my ($constants) = @_;
1794: if (defined($constants)) {
1795: if (! ref($constants)) {
1796: my %tmp = @_;
1797: $constants = \%tmp;
1.104 matthew 1798: }
1.164 matthew 1799: $self->{'constants'} = $constants;
1800: return;
1.104 matthew 1801: } else {
1.164 matthew 1802: return %{$self->{'constants'}};
1.3 www 1803: }
1804: }
1.164 matthew 1805:
1806: ##
1.165 matthew 1807: ## formulas: either set or get the formulas
1808: ##
1.164 matthew 1809: sub formulas {
1810: my $self=shift;
1811: my ($formulas) = @_;
1812: if (defined($formulas)) {
1813: if (! ref($formulas)) {
1814: my %tmp = @_;
1815: $formulas = \%tmp;
1816: }
1817: $self->{'formulas'} = $formulas;
1.165 matthew 1818: $self->{'rows'} = [];
1.164 matthew 1819: $self->{'template_cells'} = [];
1820: return;
1821: } else {
1822: return %{$self->{'formulas'}};
1.105 matthew 1823: }
1.28 www 1824: }
1825:
1.164 matthew 1826: ##
1827: ## formulas_keys: Return the keys to the formulas hash.
1828: ##
1829: sub formulas_keys {
1830: my $self = shift;
1831: my @keys = keys(%{$self->{'formulas'}});
1832: return keys(%{$self->{'formulas'}});
1.19 www 1833: }
1834:
1.164 matthew 1835: ##
1836: ## formula: Return the formula for a given cell in the spreadsheet
1837: ## returns '' if the cell does not have a formula or does not exist
1838: ##
1839: sub formula {
1840: my $self = shift;
1841: my $cell = shift;
1842: if (defined($cell) && exists($self->{'formulas'}->{$cell})) {
1843: return $self->{'formulas'}->{$cell};
1.10 www 1844: }
1.164 matthew 1845: return '';
1846: }
1847:
1848: ##
1849: ## logthis: write the input to lonnet.log
1850: ##
1851: sub logthis {
1852: my $self = shift;
1853: my $message = shift;
1854: &Apache::lonnet::logthis($self->{'type'}.':'.
1855: $self->{'uname'}.':'.$self->{'udom'}.':'.
1856: $message);
1.165 matthew 1857: return;
1.10 www 1858: }
1859:
1.164 matthew 1860: ##
1861: ## dump_formulas_to_log: makes lonnet.log huge...
1862: ##
1863: sub dump_formulas_to_log {
1864: my $self =shift;
1865: $self->logthis("Spreadsheet formulas");
1866: $self->logthis("--------------------------------------------------------");
1867: while (my ($cell, $formula) = each(%{$self->{'formulas'}})) {
1868: $self->logthis(' '.$cell.' = '.$formula);
1.153 matthew 1869: }
1.164 matthew 1870: $self->logthis("--------------------------------------------------------");}
1871:
1872: ##
1873: ## value: returns the computed value of a particular cell
1874: ##
1875: sub value {
1876: my $self = shift;
1877: my $cell = shift;
1878: if (defined($cell) && exists($self->{'values'}->{$cell})) {
1879: return $self->{'values'}->{$cell};
1.55 www 1880: }
1.164 matthew 1881: return '';
1.10 www 1882: }
1883:
1.164 matthew 1884: ##
1885: ## dump_values_to_log: makes lonnet.log huge...
1886: ##
1887: sub dump_values_to_log {
1888: my $self =shift;
1889: $self->logthis("Spreadsheet Values");
1890: $self->logthis("--------------------------------------------------------");
1891: while (my ($cell, $value) = each(%{$self->{'values'}})) {
1892: $self->logthis(' '.$cell.' = '.$value);
1893: }
1894: $self->logthis("--------------------------------------------------------");}
1895:
1896: ################################
1897: ## Helper functions ##
1898: ################################
1899: ##
1.165 matthew 1900: ## rebuild_stats: rebuilds the rows and template_cells arrays
1.164 matthew 1901: ##
1902: sub rebuild_stats {
1903: my $self = shift;
1.165 matthew 1904: $self->{'rows'}=[];
1.164 matthew 1905: $self->{'template_cells'}=[];
1906: foreach my $cell($self->formulas_keys()) {
1.166 matthew 1907: push(@{$self->{'rows'}},$1) if ($cell =~ /^A(\d+)/ && $1 != 0);
1.165 matthew 1908: push(@{$self->{'template_cells'}},$1) if ($cell =~ /^template_(\w+)/);
1.164 matthew 1909: }
1910: return;
1911: }
1.11 www 1912:
1.164 matthew 1913: ##
1914: ## template_cells returns a list of the cells defined in the template row
1915: ##
1916: sub template_cells {
1917: my $self = shift;
1918: $self->rebuild_stats() if (!@{$self->{'template_cells'}});
1919: return @{$self->{'template_cells'}};
1920: }
1.11 www 1921:
1.164 matthew 1922: ##
1.165 matthew 1923: ## rows returns a list of the names of cells defined in the A column
1.164 matthew 1924: ##
1.165 matthew 1925: sub rows {
1.164 matthew 1926: my $self = shift;
1.165 matthew 1927: $self->rebuild_stats() if (!@{$self->{'rows'}});
1928: return @{$self->{'rows'}};
1.164 matthew 1929: }
1.11 www 1930:
1.164 matthew 1931: ##
1932: ## Sigh....
1933: ##
1934: sub setothersheets {
1935: my $self = shift;
1936: my @othersheets = @_;
1937: $self->{'othersheets'} = \@othersheets;
1938: }
1.11 www 1939:
1.164 matthew 1940: ##
1941: ## rowlabels: get or set the rowlabels hash from the spreadsheet.
1942: ##
1943: sub rowlabels {
1944: my $self = shift;
1945: my ($rowlabel) = @_;
1946: if (defined($rowlabel)) {
1947: if (! ref($rowlabel)) {
1948: my %tmp = @_;
1949: $rowlabel = \%tmp;
1950: }
1951: $self->{'rowlabel'}=$rowlabel;
1952: return;
1953: } else {
1.167 matthew 1954: return %{$self->{'rowlabel'}} if (defined($self->{'rowlabel'}));
1.164 matthew 1955: }
1956: }
1.11 www 1957:
1.164 matthew 1958: ##
1959: ## gettitle: returns a title for the spreadsheet.
1960: ##
1961: sub gettitle {
1962: my $self = shift;
1963: if ($self->{'type'} eq 'classcalc') {
1964: return $self->{'coursedesc'};
1965: } elsif ($self->{'type'} eq 'studentcalc') {
1966: return 'Grades for '.$self->{'uname'}.'@'.$self->{'udom'};
1967: } elsif ($self->{'type'} eq 'assesscalc') {
1968: if (($self->{'usymb'} eq '_feedback') ||
1969: ($self->{'usymb'} eq '_evaluation') ||
1970: ($self->{'usymb'} eq '_discussion') ||
1971: ($self->{'usymb'} eq '_tutoring')) {
1972: my $title = $self->{'usymb'};
1973: $title =~ s/^_//;
1974: $title = ucfirst($title);
1975: return $title;
1976: }
1977: return if (! defined($self->{'mapid'}) ||
1978: $self->{'mapid'} !~ /^\d+$/);
1979: my $mapid = $self->{'mapid'};
1980: return if (! defined($self->{'resid'}) ||
1981: $self->{'resid'} !~ /^\d+$/);
1982: my $resid = $self->{'resid'};
1983: my %course_db;
1984: tie(%course_db,'GDBM_File',$self->{'coursefilename'}.'.db',
1985: &GDBM_READER(),0640);
1986: return if (! tied(%course_db));
1987: my $key = 'title_'.$mapid.'.'.$resid;
1988: my $title = '';
1989: if (exists($course_db{$key})) {
1990: $title = $course_db{$key};
1991: } else {
1992: $title = $self->{'usymb'};
1993: }
1994: untie (%course_db);
1995: return $title;
1996: }
1997: }
1.11 www 1998:
1.164 matthew 1999: #
2000: # Export of A-row
2001: #
2002: sub exportdata {
2003: my $self=shift;
2004: my @exportarray=();
2005: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2006: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
2007: push(@exportarray,$self->value($_.'0'));
2008: }
2009: return @exportarray;
2010: }
1.11 www 2011:
1.164 matthew 2012: ##
2013: ## update_student_sheet: experimental function
2014: ##
2015: sub update_student_sheet{
2016: my $self = shift;
2017: my ($r,$c) = @_;
2018: # Load in the studentcalc sheet
2019: $self->readsheet('default_studentcalc');
2020: # Determine the structure (contained assessments, etc) of the sheet
2021: $self->updatesheet();
2022: # Load in the cached sheets for this student
2023: $self->cachedssheets();
2024: # Load in the (possibly cached) data from the assessment sheets
2025: $self->loadstudent($r,$c);
2026: # Compute the sheet
2027: $self->calcsheet();
2028: }
1.11 www 2029:
1.164 matthew 2030: #
2031: # sort_indicies: returns an ordered list of the rows of the spreadsheet
2032: #
2033: sub sort_indicies {
2034: my $self = shift;
2035: my @sortidx=();
1.104 matthew 2036: #
1.164 matthew 2037: if ($self->{'type'} eq 'classcalc') {
2038: my @sortby=(undef);
2039: # Skip row 0
2040: for (my $row=1;$row<=$self->{'maxrow'};$row++) {
2041: my (undef,$sname,$sdom,$fullname,$section,$id) =
2042: split(':',$self->{'rowlabel'}->{$self->formula('A'.$row)});
2043: push (@sortby, lc($fullname));
2044: push (@sortidx, $row);
2045: }
2046: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
2047: } elsif ($self->{'type'} eq 'studentcalc') {
2048: my @sortby1=(undef);
2049: my @sortby2=(undef);
2050: # Skip row 0
2051: for (my $row=1;$row<=$self->{'maxrow'};$row++) {
2052: my ($key,undef) = split(/__&&&\__/,$self->formula('A'.$row));
2053: my $rowlabel = $self->{'rowlabel'}->{$key};
2054: my (undef,$symb,$mapid,$resid,$title,$ufn) =
2055: split(':',$rowlabel);
2056: $ufn = &Apache::lonnet::unescape($ufn);
2057: $symb = &Apache::lonnet::unescape($symb);
2058: $title = &Apache::lonnet::unescape($title);
2059: my ($sequence) = ($symb =~ /\/([^\/]*\.sequence)/);
2060: if ($sequence eq '') {
2061: $sequence = $symb;
2062: }
2063: push (@sortby1, $sequence);
2064: push (@sortby2, $title);
2065: push (@sortidx, $row);
2066: }
2067: @sortidx = sort { $sortby1[$a] cmp $sortby1[$b] ||
2068: $sortby2[$a] cmp $sortby2[$b] } @sortidx;
2069: } else {
2070: my @sortby=(undef);
2071: # Skip row 0
2072: $self->sync_safe_space();
2073: for (my $row=1;$row<=$self->{'maxrow'};$row++) {
2074: push (@sortby, $self->{'safe'}->reval('$f{"A'.$row.'"}'));
2075: push (@sortidx, $row);
2076: }
2077: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1.104 matthew 2078: }
1.164 matthew 2079: return @sortidx;
1.11 www 2080: }
2081:
1.164 matthew 2082: #############################################################
2083: ### ###
2084: ### Spreadsheet Output Routines ###
2085: ### ###
2086: #############################################################
1.133 matthew 2087:
1.164 matthew 2088: ############################################
2089: ## HTML output routines ##
2090: ############################################
2091: sub html_editable_cell {
2092: my ($cell,$bgcolor) = @_;
2093: my $result;
2094: my ($name,$formula,$value);
2095: if (defined($cell)) {
2096: $name = $cell->{'name'};
2097: $formula = $cell->{'formula'};
2098: $value = $cell->{'value'};
2099: }
2100: $name = '' if (! defined($name));
2101: $formula = '' if (! defined($formula));
2102: if (! defined($value)) {
2103: $value = '<font color="'.$bgcolor.'">#</font>';
2104: if ($formula ne '') {
2105: $value = '<i>undefined value</i>';
1.148 matthew 2106: }
1.164 matthew 2107: } elsif ($value =~ /^\s*$/ ) {
2108: $value = '<font color="'.$bgcolor.'">#</font>';
1.133 matthew 2109: } else {
1.164 matthew 2110: $value = &HTML::Entities::encode($value) if ($value !~/ /);
2111: }
2112: # Make the formula safe for outputting
2113: $formula =~ s/\'/\"/g;
2114: # The formula will be parsed by the browser *twice* before being
2115: # displayed to the user for editing.
2116: $formula = &HTML::Entities::encode(&HTML::Entities::encode($formula));
2117: # Escape newlines so they make it into the edit window
2118: $formula =~ s/\n/\\n/gs;
2119: # Glue everything together
2120: $result .= "<a href=\"javascript:celledit(\'".
2121: $name."','".$formula."');\">".$value."</a>";
1.133 matthew 2122: return $result;
2123: }
2124:
1.164 matthew 2125: sub html_uneditable_cell {
2126: my ($cell,$bgcolor) = @_;
2127: my $value = (defined($cell) ? $cell->{'value'} : '');
2128: $value = &HTML::Entities::encode($value) if ($value !~/ /);
2129: return ' '.$value.' ';
1.133 matthew 2130: }
2131:
1.164 matthew 2132: sub outsheet_html {
2133: my $self = shift;
2134: my ($r) = @_;
2135: my ($num_uneditable,$realm,$row_type);
2136: my $requester_is_student = ($ENV{'request.role'} =~ /^st\./);
2137: if ($self->{'type'} eq 'assesscalc') {
2138: $num_uneditable = 1;
2139: $realm = 'Assessment';
2140: $row_type = 'Item';
2141: } elsif ($self->{'type'} eq 'studentcalc') {
2142: $num_uneditable = 26;
2143: $realm = 'User';
2144: $row_type = 'Assessment';
2145: } elsif ($self->{'type'} eq 'classcalc') {
2146: $num_uneditable = 26;
2147: $realm = 'Course';
2148: $row_type = 'Student';
1.125 matthew 2149: } else {
1.164 matthew 2150: return; # error
2151: }
2152: ####################################
2153: # Print out header table
2154: ####################################
2155: my $num_left = 52-$num_uneditable;
2156: my $tabledata =<<"END";
2157: <table border="2">
2158: <tr>
2159: <th colspan="2" rowspan="2"><font size="+2">$realm</font></th>
2160: <td bgcolor="#FFDDDD" colspan="$num_uneditable">
2161: <b><font size="+1">Import</font></b></td>
2162: <td colspan="$num_left">
2163: <b><font size="+1">Calculations</font></b></td>
2164: </tr><tr>
2165: END
2166: my $label_num = 0;
2167: foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
2168: if ($label_num<$num_uneditable) {
2169: $tabledata.='<td bgcolor="#FFDDDD">';
2170: } else {
2171: $tabledata.='<td>';
2172: }
2173: $tabledata.="<b><font size=+1>$_</font></b></td>";
2174: $label_num++;
2175: }
2176: $tabledata.="</tr>\n";
2177: $r->print($tabledata);
2178: ####################################
2179: # Print out template row
2180: ####################################
2181: my ($num_cols_output,$row_html,$rowlabel,@rowdata);
2182:
2183: if (! $requester_is_student) {
2184: ($rowlabel,@rowdata) = $self->get_row('-');
2185: $row_html = '<tr><td>'.$self->format_html_rowlabel($rowlabel).'</td>';
2186: $num_cols_output = 0;
2187: foreach my $cell (@rowdata) {
2188: if ($requester_is_student ||
2189: $num_cols_output++ < $num_uneditable) {
2190: $row_html .= '<td bgcolor="#FFDDDD">';
2191: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
2192: } else {
2193: $row_html .= '<td bgcolor="#EOFFDD">';
2194: $row_html .= &html_editable_cell($cell,'#E0FFDD');
2195: }
2196: $row_html .= '</td>';
2197: }
2198: $row_html.= "</tr>\n";
2199: $r->print($row_html);
2200: }
2201: ####################################
2202: # Print out summary/export row
2203: ####################################
2204: ($rowlabel,@rowdata) = $self->get_row('0');
2205: $row_html = '<tr><td>'.$self->format_html_rowlabel($rowlabel).'</td>';
2206: $num_cols_output = 0;
2207: foreach my $cell (@rowdata) {
2208: if ($num_cols_output++ < 26 && ! $requester_is_student) {
2209: $row_html .= '<td bgcolor="#CCCCFF">';
2210: $row_html .= &html_editable_cell($cell,'#CCCCFF');
2211: } else {
2212: $row_html .= '<td bgcolor="#DDCCFF">';
2213: $row_html .= &html_uneditable_cell($cell,'#CCCCFF');
2214: }
2215: $row_html .= '</td>';
1.125 matthew 2216: }
1.164 matthew 2217: $row_html.= "</tr>\n";
2218: $r->print($row_html);
2219: $r->print('</table>');
2220: ####################################
2221: # Prepare to output rows
2222: ####################################
2223: my @Rows = $self->sort_indicies();
1.102 matthew 2224: #
1.164 matthew 2225: # Loop through the rows and output them one at a time
2226: my $rows_output=0;
2227: foreach my $rownum (@Rows) {
2228: my ($rowlabel,@rowdata) = $self->get_row($rownum);
2229: next if ($rowlabel =~ /^\s*$/);
2230: next if (($self->{'type'} eq 'assesscalc') &&
2231: (! $ENV{'form.showall'}) &&
2232: ($rowdata[0]->{'value'} =~ /^\s*$/));
2233: if (! $ENV{'form.showall'} &&
2234: $self->{'type'} =~ /^(studentcalc|classcalc)$/) {
2235: my $row_is_empty = 1;
2236: foreach my $cell (@rowdata) {
2237: if ($cell->{'value'} !~ /^\s*$/) {
2238: $row_is_empty = 0;
2239: last;
2240: }
2241: }
2242: next if ($row_is_empty);
2243: }
2244: #
2245: my $defaultbg='#E0FF';
2246: #
2247: my $row_html ="\n".'<tr><td><b><font size=+1>'.$rownum.
2248: '</font></b></td>';
2249: #
2250: if ($self->{'type'} eq 'classcalc') {
2251: $row_html.='<td>'.$self->format_html_rowlabel($rowlabel).'</td>';
2252: # Output links for each student?
2253: # Nope, that is already done for us in format_html_rowlabel
2254: # (for now)
2255: } elsif ($self->{'type'} eq 'studentcalc') {
2256: my $ufn = (split(/:/,$rowlabel))[5];
2257: $row_html.='<td>'.$self->format_html_rowlabel($rowlabel);
2258: $row_html.= '<br>'.
2259: '<select name="sel_'.$rownum.'" '.
2260: 'onChange="changesheet('.$rownum.')">'.
2261: '<option name="default">Default</option>';
2262: foreach (@{$self->{'othersheets'}}) {
2263: $row_html.='<option name="'.$_.'"';
2264: if ($ufn eq $_) {
2265: $row_html.=' selected';
2266: }
2267: $row_html.='>'.$_.'</option>';
2268: }
2269: $row_html.='</select></td>';
2270: } elsif ($self->{'type'} eq 'assesscalc') {
2271: $row_html.='<td>'.$self->format_html_rowlabel($rowlabel).'</td>';
2272: }
2273: #
2274: my $shown_cells = 0;
2275: foreach my $cell (@rowdata) {
2276: my $value = $cell->{'value'};
2277: my $formula = $cell->{'formula'};
2278: my $cellname = $cell->{'name'};
2279: #
2280: my $bgcolor;
2281: if ($shown_cells && ($shown_cells/5 == int($shown_cells/5))) {
2282: $bgcolor = $defaultbg.'99';
2283: } else {
2284: $bgcolor = $defaultbg.'DD';
2285: }
2286: $bgcolor='#FFDDDD' if ($shown_cells < $num_uneditable);
2287: #
2288: $row_html.='<td bgcolor='.$bgcolor.'>';
2289: if ($requester_is_student || $shown_cells < $num_uneditable) {
2290: $row_html .= &html_uneditable_cell($cell,$bgcolor);
2291: } else {
2292: $row_html .= &html_editable_cell($cell,$bgcolor);
2293: }
2294: $row_html.='</td>';
2295: $shown_cells++;
2296: }
2297: if ($row_html) {
2298: if ($rows_output % 25 == 0) {
2299: $r->print("</table>\n<br>\n");
2300: $r->rflush();
2301: $r->print('<table border=2>'.
2302: '<tr><td> <td>'.$row_type.'</td>'.
2303: '<td>'.
2304: join('</td><td>',
2305: (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
2306: 'abcdefghijklmnopqrstuvwxyz'))).
2307: "</td></tr>\n");
2308: }
2309: $rows_output++;
2310: $r->print($row_html);
1.118 matthew 2311: }
2312: }
1.102 matthew 2313: #
1.164 matthew 2314: $r->print('</table>');
1.102 matthew 2315: #
1.164 matthew 2316: # Debugging code (be sure to uncomment errorlog code in safe space):
1.102 matthew 2317: #
1.164 matthew 2318: # $r->print("\n<pre>");
2319: # $r->print(&geterrorlog($self));
2320: # $r->print("\n</pre>");
2321: return 1;
2322: }
2323:
2324: ############################################
2325: ## csv output routines ##
2326: ############################################
2327: sub outsheet_csv {
2328: my $self = shift;
2329: my ($r) = @_;
2330: my $csvdata = '';
2331: my @Values;
2332: ####################################
2333: # Prepare to output rows
2334: ####################################
2335: my @Rows = $self->sort_indicies();
1.102 matthew 2336: #
1.164 matthew 2337: # Loop through the rows and output them one at a time
2338: my $rows_output=0;
2339: foreach my $rownum (@Rows) {
2340: my ($rowlabel,@rowdata) = $self->get_row($rownum);
2341: next if ($rowlabel =~ /^\s*$/);
2342: push (@Values,$self->format_csv_rowlabel($rowlabel));
2343: foreach my $cell (@rowdata) {
2344: push (@Values,'"'.$cell->{'value'}.'"');
1.78 matthew 2345: }
1.164 matthew 2346: $csvdata.= join(',',@Values)."\n";
2347: @Values = ();
1.102 matthew 2348: }
2349: #
1.164 matthew 2350: # Write the CSV data to a file and serve up a link
2351: #
2352: my $filename = '/prtspool/'.
2353: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
2354: time.'_'.rand(1000000000).'.csv';
2355: my $file;
2356: unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
2357: $r->log_error("Couldn't open $filename for output $!");
2358: $r->print("Problems occured in writing the csv file. ".
2359: "This error has been logged. ".
2360: "Please alert your LON-CAPA administrator.");
2361: $r->print("<pre>\n".$csvdata."</pre>\n");
2362: return 0;
1.119 matthew 2363: }
1.164 matthew 2364: print $file $csvdata;
2365: close($file);
2366: $r->print('<br /><br />'.
2367: '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
1.102 matthew 2368: #
1.164 matthew 2369: return 1;
1.23 www 2370: }
1.5 www 2371:
1.164 matthew 2372: ############################################
2373: ## Excel output routines ##
2374: ############################################
2375: sub outsheet_recursive_excel {
2376: my $self = shift;
2377: my ($r) = @_;
2378: my $c = $r->connection;
2379: return undef if ($self->{'type'} ne 'classcalc');
2380: my ($workbook,$filename) = $self->create_excel_spreadsheet($r);
2381: return undef if (! defined($workbook));
1.136 matthew 2382: #
1.164 matthew 2383: # Create main worksheet
2384: my $main_worksheet = $workbook->addworksheet('main');
1.136 matthew 2385: #
1.164 matthew 2386: # Figure out who the students are
2387: my %f=$self->formulas();
2388: my $count = 0;
2389: $r->print(<<END);
2390: <p>
2391: Compiling Excel Workbook with a worksheet for each student.
2392: </p><p>
2393: This operation may take longer than a complete recalculation of the
2394: spreadsheet.
2395: </p><p>
2396: To abort this operation, hit the stop button on your browser.
2397: </p><p>
2398: A link to the spreadsheet will be available at the end of this process.
2399: </p>
2400: <p>
2401: END
2402: $r->rflush();
2403: my $starttime = time;
2404: foreach my $rownum ($self->sort_indicies()) {
2405: $count++;
2406: my ($sname,$sdom) = split(':',$f{'A'.$rownum});
2407: my $student_excel_worksheet=$workbook->addworksheet($sname.'@'.$sdom);
2408: # Create a new spreadsheet
2409: my $studentsheet = &Apache::lonspreadsheet::Spreadsheet->new
2410: ($sname,$sdom,'studentcalc',undef);
2411: # Read in the spreadsheet definition
2412: $studentsheet->update_student_sheet($r,$c);
2413: # Stuff the sheet into excel
2414: $studentsheet->export_sheet_as_excel($student_excel_worksheet);
2415: my $totaltime = int((time - $starttime) / $count * $self->{'maxrow'});
2416: my $timeleft = int((time - $starttime) / $count * ($self->{'maxrow'} - $count));
2417: if ($count % 5 == 0) {
2418: $r->print($count.' students completed.'.
2419: ' Time remaining: '.$timeleft.' sec. '.
2420: ' Estimated total time: '.$totaltime." sec <br />\n");
2421: $r->rflush();
2422: }
2423: if(defined($c) && ($c->aborted())) {
2424: last;
2425: }
2426: }
1.136 matthew 2427: #
1.164 matthew 2428: if(! $c->aborted() ) {
2429: $r->print('All students spreadsheets completed!<br />');
2430: $r->rflush();
1.136 matthew 2431: #
1.164 matthew 2432: # &export_sheet_as_excel fills $worksheet with the data from $sheet
2433: $self->export_sheet_as_excel($main_worksheet);
1.136 matthew 2434: #
1.164 matthew 2435: $workbook->close();
2436: # Okay, the spreadsheet is taken care of, so give the user a link.
2437: $r->print('<br /><br />'.
2438: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
2439: } else {
2440: $workbook->close(); # Not sure how necessary this is.
2441: #unlink('/home/httpd'.$filename); # No need to keep this around?
1.136 matthew 2442: }
1.164 matthew 2443: return 1;
2444: }
1.136 matthew 2445:
1.164 matthew 2446: sub outsheet_excel {
2447: my $self = shift;
2448: my ($r) = @_;
2449: my ($workbook,$filename) = $self->create_excel_spreadsheet($r);
2450: return undef if (! defined($workbook));
2451: my $sheetname;
2452: if ($self->{'type'} eq 'classcalc') {
2453: $sheetname = 'Main';
2454: } elsif ($self->{'type'} eq 'studentcalc') {
2455: $sheetname = $self->{'uname'}.'@'.$self->{'udom'};
2456: } elsif ($self->{'type'} eq 'assesscalc') {
2457: $sheetname = $self->{'uname'}.'@'.$self->{'udom'}.' assessment';
2458: }
2459: my $worksheet = $workbook->addworksheet($sheetname);
2460: #
2461: # &export_sheet_as_excel fills $worksheet with the data from $sheet
2462: $self->export_sheet_as_excel($worksheet);
2463: #
2464: $workbook->close();
2465: # Okay, the spreadsheet is taken care of, so give the user a link.
2466: $r->print('<br /><br />'.
2467: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
2468: return 1;
1.136 matthew 2469: }
2470:
1.164 matthew 2471: sub create_excel_spreadsheet {
2472: my $self = shift;
2473: my ($r) = @_;
2474: my $filename = '/prtspool/'.
2475: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
2476: time.'_'.rand(1000000000).'.xls';
2477: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2478: if (! defined($workbook)) {
2479: $r->log_error("Error creating excel spreadsheet $filename: $!");
2480: $r->print("Problems creating new Excel file. ".
2481: "This error has been logged. ".
2482: "Please alert your LON-CAPA administrator");
2483: return undef;
2484: }
1.128 matthew 2485: #
1.164 matthew 2486: # The excel spreadsheet stores temporary data in files, then put them
2487: # together. If needed we should be able to disable this (memory only).
2488: # The temporary directory must be specified before calling 'addworksheet'.
2489: # File::Temp is used to determine the temporary directory.
2490: $workbook->set_tempdir('/home/httpd/perl/tmp');
1.128 matthew 2491: #
1.164 matthew 2492: # Determine the name to give the worksheet
2493: return ($workbook,$filename);
2494: }
2495:
2496: sub export_sheet_as_excel {
2497: my $self = shift;
2498: my $worksheet = shift;
1.136 matthew 2499: #
1.164 matthew 2500: my $rows_output = 0;
2501: my $cols_output = 0;
2502: ####################################
2503: # Write an identifying row #
2504: ####################################
2505: my @Headerinfo = ($self->{'coursedesc'});
2506: my $title = $self->gettitle();
2507: $cols_output = 0;
2508: if (defined($title)) {
2509: $worksheet->write($rows_output++,$cols_output++,$title);
2510: }
2511: ####################################
2512: # Write the summary/export row #
2513: ####################################
2514: my ($rowlabel,@rowdata) = &get_row($self,'0');
2515: my $label = &format_excel_rowlabel($self,$rowlabel);
2516: $cols_output = 0;
2517: $worksheet->write($rows_output,$cols_output++,$label);
2518: foreach my $cell (@rowdata) {
2519: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
2520: }
2521: $rows_output+= 2; # Skip a row, just for fun
2522: ####################################
2523: # Prepare to output rows
2524: ####################################
2525: my @Rows = &sort_indicies($self);
1.136 matthew 2526: #
1.164 matthew 2527: # Loop through the rows and output them one at a time
2528: foreach my $rownum (@Rows) {
2529: my ($rowlabel,@rowdata) = &get_row($self,$rownum);
2530: next if ($rowlabel =~ /^[\s]*$/);
2531: $cols_output = 0;
2532: my $label = &format_excel_rowlabel($self,$rowlabel);
2533: if ( ! $ENV{'form.showall'} &&
2534: $self->{'type'} =~ /^(studentcalc|classcalc)$/) {
2535: my $row_is_empty = 1;
2536: foreach my $cell (@rowdata) {
2537: if ($cell->{'value'} !~ /^\s*$/) {
2538: $row_is_empty = 0;
2539: last;
2540: }
2541: }
2542: next if ($row_is_empty);
2543: }
1.168 matthew 2544: $worksheet->write($rows_output,$cols_output++,$rownum);
1.164 matthew 2545: $worksheet->write($rows_output,$cols_output++,$label);
2546: if (ref($label)) {
2547: $cols_output = (scalar(@$label));
1.104 matthew 2548: }
1.164 matthew 2549: foreach my $cell (@rowdata) {
2550: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1.136 matthew 2551: }
1.164 matthew 2552: $rows_output++;
1.136 matthew 2553: }
1.164 matthew 2554: return;
1.136 matthew 2555: }
2556:
1.164 matthew 2557: ############################################
2558: ## XML output routines ##
2559: ############################################
2560: sub outsheet_xml {
2561: my $self = shift;
2562: my ($r) = @_;
2563: ## Someday XML
2564: ## Will be rendered for the user
2565: ## But not on this day
1.5 www 2566: }
1.3 www 2567:
1.164 matthew 2568: ##
2569: ## Outsheet - calls other outsheet_* functions
2570: ##
2571: sub outsheet {
2572: my $self = shift;
2573: my ($r)=@_;
2574: if (! exists($ENV{'form.output'})) {
2575: $ENV{'form.output'} = 'HTML';
1.39 www 2576: }
1.164 matthew 2577: if (lc($ENV{'form.output'}) eq 'csv') {
2578: $self->outsheet_csv($r);
2579: } elsif (lc($ENV{'form.output'}) eq 'excel') {
2580: $self->outsheet_excel($r);
2581: } elsif (lc($ENV{'form.output'}) eq 'recursive excel') {
2582: $self->outsheet_recursive_excel($r);
2583: # } elsif (lc($ENV{'form.output'}) eq 'xml' ) {
2584: # $self->outsheet_xml($r);
2585: } else {
2586: $self->outsheet_html($r);
1.78 matthew 2587: }
1.16 www 2588: }
2589:
1.109 matthew 2590: #
1.164 matthew 2591: # othersheets: Returns the list of other spreadsheets available
2592: #
2593: sub othersheets {
2594: my $self = shift;
2595: my ($stype)=@_;
2596: $stype = $self->{'type'} if (! defined($stype));
2597: #
2598: my $cnum = $self->{'cnum'};
2599: my $cdom = $self->{'cdom'};
2600: my $chome = $self->{'chome'};
1.135 matthew 2601: #
1.164 matthew 2602: my @alternatives=();
2603: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
2604: my ($tmp) = keys(%results);
2605: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
2606: @alternatives = sort (keys(%results));
1.78 matthew 2607: }
1.164 matthew 2608: return @alternatives;
1.24 www 2609: }
2610:
1.109 matthew 2611: #
1.164 matthew 2612: # Parse a spreadsheet
2613: #
2614: sub parse_sheet {
2615: # $sheetxml is a scalar reference or a scalar
2616: my ($sheetxml) = @_;
2617: if (! ref($sheetxml)) {
2618: my $tmp = $sheetxml;
2619: $sheetxml = \$tmp;
2620: }
2621: my %f;
2622: my $parser=HTML::TokeParser->new($sheetxml);
2623: my $token;
2624: while ($token=$parser->get_token) {
2625: if ($token->[0] eq 'S') {
2626: if ($token->[1] eq 'field') {
2627: $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
2628: $parser->get_text('/field');
2629: }
2630: if ($token->[1] eq 'template') {
2631: $f{'template_'.$token->[2]->{'col'}}=
2632: $parser->get_text('/template');
2633: }
1.104 matthew 2634: }
1.6 www 2635: }
1.164 matthew 2636: return \%f;
2637: }
2638:
2639: sub readsheet {
2640: my $self = shift;
2641: my ($fn)=@_;
1.109 matthew 2642: #
1.164 matthew 2643: my $stype = $self->{'type'};
2644: my $cnum = $self->{'cnum'};
2645: my $cdom = $self->{'cdom'};
2646: my $chome = $self->{'chome'};
1.109 matthew 2647: #
1.164 matthew 2648: if (! defined($fn)) {
2649: # There is no filename. Look for defaults in course and global, cache
2650: unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
2651: my %tmphash = &Apache::lonnet::get('environment',
2652: ['spreadsheet_default_'.$stype],
2653: $cdom,$cnum);
2654: my ($tmp) = keys(%tmphash);
2655: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
2656: $fn = 'default_'.$stype;
2657: } else {
2658: $fn = $tmphash{'spreadsheet_default_'.$stype};
2659: }
2660: unless (($fn) && ($fn!~/^error\:/)) {
2661: $fn='default_'.$stype;
2662: }
2663: $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn;
1.104 matthew 2664: }
1.29 www 2665: }
1.164 matthew 2666: # $fn now has a value
2667: $self->{'filename'} = $fn;
2668: # see if sheet is cached
1.167 matthew 2669: if (exists($spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn})) {
2670:
2671: my %tmp = split(/___;___/,
2672: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn});
1.164 matthew 2673: $self->formulas(\%tmp);
2674: } else {
2675: # Not cached, need to read
2676: my %f=();
2677: if ($fn=~/^default\_/) {
2678: my $sheetxml='';
2679: my $fh;
2680: my $dfn=$fn;
2681: $dfn=~s/\_/\./g;
2682: if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
2683: $sheetxml=join('',<$fh>);
2684: } else {
2685: # $sheetxml='<field row="0" col="A">"Error"</field>';
2686: $sheetxml='<field row="0" col="A"></field>';
2687: }
2688: %f=%{&parse_sheet(\$sheetxml)};
2689: } elsif($fn=~/\/*\.spreadsheet$/) {
2690: my $sheetxml=&Apache::lonnet::getfile
2691: (&Apache::lonnet::filelocation('',$fn));
2692: if ($sheetxml == -1) {
2693: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
2694: .$fn.'"</field>';
2695: }
2696: %f=%{&parse_sheet(\$sheetxml)};
2697: } else {
2698: my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
2699: my ($tmp) = keys(%tmphash);
2700: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
2701: foreach (keys(%tmphash)) {
2702: $f{$_}=$tmphash{$_};
2703: }
2704: } else {
2705: # Unable to grab the specified spreadsheet,
2706: # so we get the default ones instead.
2707: $fn = 'default_'.$stype;
2708: $self->{'filename'} = $fn;
2709: my $dfn = $fn;
2710: $dfn =~ s/\_/\./g;
2711: my $sheetxml;
2712: if (my $fh=Apache::File->new($includedir.'/'.$dfn)) {
2713: $sheetxml = join('',<$fh>);
2714: } else {
2715: $sheetxml='<field row="0" col="A">'.
2716: '"Unable to load spreadsheet"</field>';
1.104 matthew 2717: }
1.164 matthew 2718: %f=%{&parse_sheet(\$sheetxml)};
1.104 matthew 2719: }
1.6 www 2720: }
1.164 matthew 2721: # Cache and set
2722: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
2723: $self->formulas(\%f);
1.78 matthew 2724: }
1.6 www 2725: }
2726:
1.164 matthew 2727: # ------------------------------------------------------------ Save spreadsheet
2728: sub writesheet {
2729: my $self = shift;
2730: my ($makedef)=@_;
2731: my $cid=$self->{'cid'};
2732: if (&Apache::lonnet::allowed('opa',$cid)) {
2733: my %f=$self->formulas();
2734: my $stype= $self->{'type'};
2735: my $cnum = $self->{'cnum'};
2736: my $cdom = $self->{'cdom'};
2737: my $chome= $self->{'chome'};
2738: my $fn = $self->{'filename'};
2739: # Cache new sheet
2740: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
2741: # Write sheet
2742: foreach (keys(%f)) {
2743: delete($f{$_}) if ($f{$_} eq 'import');
2744: }
2745: my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
2746: if ($reply eq 'ok') {
2747: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
2748: {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
2749: $cdom,$cnum);
2750: if ($reply eq 'ok') {
2751: if ($makedef) {
2752: $reply = &Apache::lonnet::put('environment',
2753: {'spreadsheet_default_'.$stype => $fn },
2754: $cdom,$cnum);
2755: if ($reply eq 'ok' &&
2756: ($self->{'type'} eq 'studentcalc' ||
2757: $self->{'type'} eq 'assesscalc')) {
2758: # Expire the spreadsheets of the other students.
2759: &Apache::lonnet::expirespread('','','studentcalc','');
2760: }
2761: return $reply;
2762: }
2763: return $reply;
2764: }
2765: return $reply;
2766: }
2767: return $reply;
2768: }
2769: return 'unauthorized';
1.10 www 2770: }
2771:
1.164 matthew 2772: # ----------------------------------------------- Make a temp copy of the sheet
2773: # "Modified workcopy" - interactive only
2774: #
2775: sub tmpwrite {
2776: my $self = shift;
2777: my $fn=$ENV{'user.name'}.'_'.
2778: $ENV{'user.domain'}.'_spreadsheet_'.$self->{'usymb'}.'_'.
2779: $self->{'filename'};
2780: $fn=~s/\W/\_/g;
2781: $fn=$tmpdir.$fn.'.tmp';
2782: my $fh;
2783: if ($fh=Apache::File->new('>'.$fn)) {
2784: my %f = $self->formulas();
2785: while( my ($cell,$formula) = each(%f)) {
2786: print $fh &Apache::lonnet::escape($cell)."=".&Apache::lonnet::escape($formula)."\n";
2787: }
1.78 matthew 2788: }
1.10 www 2789: }
2790:
1.28 www 2791:
1.164 matthew 2792: # ---------------------------------------------------------- Read the temp copy
2793: sub tmpread {
2794: my $self = shift;
2795: my ($nfield,$nform)=@_;
2796: my $fn=$ENV{'user.name'}.'_'.
2797: $ENV{'user.domain'}.'_spreadsheet_'.$self->{'usymb'}.'_'.
2798: $self->{'filename'};
2799: $fn=~s/\W/\_/g;
2800: $fn=$tmpdir.$fn.'.tmp';
2801: my $fh;
2802: my %fo=();
2803: my $countrows=0;
2804: if ($fh=Apache::File->new($fn)) {
2805: while (<$fh>) {
2806: chomp;
2807: my ($cell,$formula) = split(/=/);
2808: $cell = &Apache::lonnet::unescape($cell);
2809: $formula = &Apache::lonnet::unescape($formula);
2810: $fo{$cell} = $formula;
2811: }
2812: }
2813: if ($nform eq 'changesheet') {
2814: $fo{'A'.$nfield}=(split(/__&&&\__/,$fo{'A'.$nfield}))[0];
2815: unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
2816: $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
2817: }
1.28 www 2818: } else {
1.164 matthew 2819: if ($nfield) { $fo{$nfield}=$nform; }
1.28 www 2820: }
1.164 matthew 2821: $self->formulas(\%fo);
1.28 www 2822: }
2823:
1.164 matthew 2824: ##################################################################
2825: ## Row label formatting routines ##
2826: ##################################################################
2827: sub format_html_rowlabel {
2828: my $self = shift;
2829: my $rowlabel = shift;
2830: return '' if ($rowlabel eq '');
2831: my ($type,$labeldata) = split(':',$rowlabel,2);
2832: my $result = '';
2833: if ($type eq 'symb') {
2834: my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
2835: $ufn = 'default' if (!defined($ufn) || $ufn eq '');
2836: $ufn = &Apache::lonnet::unescape($ufn);
2837: $symb = &Apache::lonnet::unescape($symb);
2838: $title = &Apache::lonnet::unescape($title);
2839: $result = '<a href="/adm/assesscalc?usymb='.$symb.
2840: '&uname='.$self->{'uname'}.'&udom='.$self->{'udom'}.
2841: '&ufn='.$ufn.
2842: '&mapid='.$mapid.'&resid='.$resid.'">'.$title.'</a>';
2843: } elsif ($type eq 'student') {
2844: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2845: if ($fullname =~ /^\s*$/) {
2846: $fullname = $sname.'@'.$sdom;
2847: }
2848: $result ='<a href="/adm/studentcalc?uname='.$sname.
2849: '&udom='.$sdom.'">';
2850: $result.=$section.' '.$id." ".$fullname.'</a>';
2851: } elsif ($type eq 'parameter') {
2852: $result = $labeldata;
1.28 www 2853: } else {
1.164 matthew 2854: $result = '<b><font size=+1>'.$rowlabel.'</font></b>';
1.28 www 2855: }
1.164 matthew 2856: return $result;
1.28 www 2857: }
2858:
1.164 matthew 2859: sub format_csv_rowlabel {
2860: my $self = shift;
2861: my $rowlabel = shift;
2862: return '' if ($rowlabel eq '');
2863: my ($type,$labeldata) = split(':',$rowlabel,2);
2864: my $result = '';
2865: if ($type eq 'symb') {
2866: my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
2867: $ufn = &Apache::lonnet::unescape($ufn);
2868: $symb = &Apache::lonnet::unescape($symb);
2869: $title = &Apache::lonnet::unescape($title);
2870: $result = $title;
2871: } elsif ($type eq 'student') {
2872: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2873: $result = join('","',($sname,$sdom,$fullname,$section,$id));
2874: } elsif ($type eq 'parameter') {
2875: $labeldata =~ s/<br>/ /g;
2876: $result = $labeldata;
1.144 matthew 2877: } else {
1.164 matthew 2878: $result = $rowlabel;
1.144 matthew 2879: }
1.164 matthew 2880: return '"'.$result.'"';
1.47 www 2881: }
1.104 matthew 2882:
1.164 matthew 2883: sub format_excel_rowlabel {
2884: my $self = shift;
2885: my $rowlabel = shift;
2886: return '' if ($rowlabel eq '');
2887: my ($type,$labeldata) = split(':',$rowlabel,2);
2888: my $result = '';
2889: if ($type eq 'symb') {
2890: my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
2891: $ufn = &Apache::lonnet::unescape($ufn);
2892: $symb = &Apache::lonnet::unescape($symb);
2893: $title = &Apache::lonnet::unescape($title);
2894: $result = $title;
2895: } elsif ($type eq 'student') {
2896: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2897: $section = '' if (! defined($section));
2898: $id = '' if (! defined($id));
2899: my @Data = ($sname,$sdom,$fullname,$section,$id);
2900: $result = \@Data;
2901: } elsif ($type eq 'parameter') {
2902: $labeldata =~ s/<br>/ /g;
2903: $result = $labeldata;
1.47 www 2904: } else {
1.164 matthew 2905: $result = $rowlabel;
1.47 www 2906: }
1.164 matthew 2907: return $result;
1.47 www 2908: }
2909:
1.164 matthew 2910: # ---------------------------------------------- Update rows for course listing
2911: sub updateclasssheet {
2912: my $self = shift;
2913: my $cnum =$self->{'cnum'};
2914: my $cdom =$self->{'cdom'};
2915: my $cid =$self->{'cid'};
2916: my $chome =$self->{'chome'};
2917: #
2918: %Section = ();
1.104 matthew 2919: #
1.164 matthew 2920: # Read class list and row labels
2921: my $classlist = &Apache::loncoursedata::get_classlist();
2922: if (! defined($classlist)) {
2923: return 'Could not access course classlist';
2924: }
1.104 matthew 2925: #
1.164 matthew 2926: my %currentlist=();
2927: foreach my $student (keys(%$classlist)) {
2928: my ($studentDomain,$studentName,$end,$start,$id,$studentSection,
2929: $fullname,$status) = @{$classlist->{$student}};
2930: $Section{$studentName.':'.$studentDomain} = $studentSection;
2931: if ($ENV{'form.Status'} eq $status || $ENV{'form.Status'} eq 'Any') {
2932: $currentlist{$student}=join(':',('student',$studentName,
2933: $studentDomain,$fullname,
2934: $studentSection,$id));
1.104 matthew 2935: }
1.44 www 2936: }
1.104 matthew 2937: #
1.164 matthew 2938: # Find discrepancies between the course row table and this
2939: #
2940: my %f=$self->formulas();
2941: my $changed=0;
2942: #
2943: $self->{'maxrow'}=0;
2944: my %existing=();
1.104 matthew 2945: #
1.164 matthew 2946: # Now obsolete rows
1.165 matthew 2947: foreach my $rownum ($self->rows()) {
2948: my $cell = 'A'.$rownum;
2949: if ($rownum > $self->{'maxrow'}) {
2950: $self->{'maxrow'}= $rownum;
1.164 matthew 2951: }
2952: $existing{$f{$cell}}=1;
1.166 matthew 2953: if (! defined($currentlist{$f{$cell}}) && ($f{$cell}=~/^(~~~|---)/)) {
1.164 matthew 2954: $f{$cell}='!!! Obsolete';
2955: $changed=1;
1.104 matthew 2956: }
2957: }
1.164 matthew 2958: #
2959: # New and unknown keys
2960: foreach my $student (sort keys(%currentlist)) {
2961: next if ($existing{$student});
2962: $changed=1;
2963: $self->{'maxrow'}++;
2964: $f{'A'.$self->{'maxrow'}}=$student;
1.120 matthew 2965: }
1.164 matthew 2966: $self->formulas(\%f) if ($changed);
2967: #
2968: $self->rowlabels(\%currentlist);
2969: }
2970:
2971: # ----------------------------------- Update rows for student and assess sheets
2972: sub get_student_rowlabels {
2973: my $self = shift;
1.120 matthew 2974: #
1.164 matthew 2975: my %course_db;
1.135 matthew 2976: #
1.164 matthew 2977: my $stype = $self->{'type'};
2978: my $uname = $self->{'uname'};
2979: my $udom = $self->{'udom'};
1.120 matthew 2980: #
1.164 matthew 2981: $self->{'rowlabel'} = {};
1.120 matthew 2982: #
1.164 matthew 2983: my $identifier =$self->{'coursefilename'}.'_'.$stype;
1.167 matthew 2984: if (exists($rowlabel_cache{$identifier})) {
2985: my %tmp = split(/___;___/,$rowlabel_cache{$identifier});
2986: $self->rowlabels(\%tmp);
1.164 matthew 2987: } else {
2988: # Get the data and store it in the cache
2989: # Tie hash
2990: tie(%course_db,'GDBM_File',$self->{'coursefilename'}.'.db',
2991: &GDBM_READER(),0640);
2992: if (! tied(%course_db)) {
2993: return 'Could not access course data';
2994: }
2995: #
2996: my %assesslist = ();
2997: foreach ('Feedback','Evaluation','Tutoring','Discussion') {
2998: my $symb = '_'.lc($_);
2999: $assesslist{$symb} = join(':',('symb',$symb,0,0,
3000: &Apache::lonnet::escape($_)));
1.131 matthew 3001: }
1.164 matthew 3002: #
3003: while (my ($key,$srcf) = each(%course_db)) {
3004: next if ($key !~ /^src_(\d+)\.(\d+)$/);
3005: my $mapid = $1;
3006: my $resid = $2;
3007: my $id = $mapid.'.'.$resid;
3008: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
3009: my $symb=
3010: &Apache::lonnet::declutter($course_db{'map_id_'.$mapid}).
3011: '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
3012: $assesslist{$symb} ='symb:'.&Apache::lonnet::escape($symb).':'
3013: .$mapid.':'.$resid.':'.
3014: &Apache::lonnet::escape($course_db{'title_'.$id});
1.145 matthew 3015: }
1.120 matthew 3016: }
1.164 matthew 3017: untie(%course_db);
3018: # Store away the data
3019: $self->{'rowlabel'} = \%assesslist;
3020: $rowlabel_cache{$identifier}=join('___;___',%{$self->{'rowlabel'}});
1.120 matthew 3021: }
1.164 matthew 3022:
3023: }
3024:
3025: sub get_assess_rowlabels {
3026: my $self = shift;
1.131 matthew 3027: #
1.164 matthew 3028: my %course_db;
1.131 matthew 3029: #
1.164 matthew 3030: my $stype = $self->{'type'};
3031: my $uname = $self->{'uname'};
3032: my $udom = $self->{'udom'};
3033: my $usymb = $self->{'usymb'};
1.120 matthew 3034: #
1.164 matthew 3035: $self->rowlabels({});
3036: my $identifier =$self->{'coursefilename'}.'_'.$stype.'_'.$usymb;
1.131 matthew 3037: #
1.167 matthew 3038: if (exists($rowlabel_cache{$identifier})) {
3039: my %tmp = split('___;___',$rowlabel_cache{$identifier});
3040: $self->rowlabels(\%tmp);
1.164 matthew 3041: } else {
3042: # Get the data and store it in the cache
3043: # Tie hash
3044: tie(%course_db,'GDBM_File',$self->{'coursefilename'}.'.db',
3045: &GDBM_READER(),0640);
3046: if (! tied(%course_db)) {
3047: return 'Could not access course data';
3048: }
3049: #
3050: my %parameter_labels=
3051: ('timestamp' =>
3052: 'parameter:Timestamp of Last Transaction<br>timestamp',
3053: 'subnumber' =>
3054: 'parameter:Number of Submissions<br>subnumber',
3055: 'tutornumber' =>
3056: 'parameter:Number of Tutor Responses<br>tutornumber',
3057: 'totalpoints' =>
3058: 'parameter:Total Points Granted<br>totalpoints');
3059: while (my ($key,$srcf) = each(%course_db)) {
3060: next if ($key !~ /^src_(\d+)\.(\d+)$/);
3061: my $mapid = $1;
3062: my $resid = $2;
3063: my $id = $mapid.'.'.$resid;
3064: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
3065: # Loop through the metadata for this key
3066: my @Metadata = split(/,/,
3067: &Apache::lonnet::metadata($srcf,'keys'));
3068: foreach my $key (@Metadata) {
3069: next if ($key !~ /^(stores|parameter)_/);
3070: my $display=
3071: &Apache::lonnet::metadata($srcf,$key.'.display');
3072: unless ($display) {
3073: $display.=
3074: &Apache::lonnet::metadata($srcf,$key.'.name');
3075: }
3076: $display.='<br>'.$key;
3077: $parameter_labels{$key}='parameter:'.$display;
3078: } # end of foreach
3079: }
3080: }
3081: untie(%course_db);
3082: # Store away the results
3083: $self->rowlabels(\%parameter_labels);
1.167 matthew 3084: $rowlabel_cache{$identifier}=join('___;___',%parameter_labels);
1.120 matthew 3085: }
1.164 matthew 3086: }
3087:
3088: sub updatestudentassesssheet {
3089: my $self = shift;
3090: if ($self->{'type'} eq 'studentcalc') {
3091: $self->get_student_rowlabels();
1.144 matthew 3092: } else {
1.164 matthew 3093: $self->get_assess_rowlabels();
3094: }
3095: # Determine if any of the information has changed
3096: my %f=$self->formulas();
3097: my $changed=0;
3098: $self->{'maxrow'} = 0;
3099: my %existing=();
3100: # Now obsolete rows
1.165 matthew 3101: foreach my $rownum ($self->rows()) {
3102: my $cell = 'A'.$rownum;
1.164 matthew 3103: my $formula = $f{$cell};
1.165 matthew 3104: $self->{'maxrow'} = $rownum if ($rownum > $self->{'maxrow'});
1.164 matthew 3105: my ($usy,$ufn)=split(/__&&&\__/,$formula);
3106: $existing{$usy}=1;
3107: if ( ! exists($self->{'rowlabel'}->{$usy}) ||
3108: ! defined($self->{'rowlabel'}->{$usy}) ||
3109: ($formula =~ /^(~~~|---)/) ||
3110: ($formula =~ /^\s*$/)) {
3111: $f{$cell}='!!! Obsolete';
3112: $changed=1;
3113: }
3114: }
3115: # New and unknown keys
3116: my %keys_hates_me = $self->rowlabels();
3117: foreach (keys(%keys_hates_me)) {
3118: unless ($existing{$_}) {
3119: $changed=1;
3120: $self->{'maxrow'}++;
3121: $f{'A'.$self->{'maxrow'}}=$_;
3122: }
1.78 matthew 3123: }
1.164 matthew 3124: $self->formulas(\%f) if ($changed);
3125: # $self->dump_formulas_to_log();
1.44 www 3126: }
1.104 matthew 3127:
1.164 matthew 3128: # ------------------------------------------------ Load data for one assessment
3129: sub loadstudent{
3130: my $self = shift;
3131: my ($r,$c)=@_;
3132: my %constants = ();
3133: my %formulas = $self->formulas();
3134: $cachedassess = $self->{'uname'}.':'.$self->{'udom'};
3135: # Get ALL the student preformance data
1.169 ! matthew 3136: my @tmp = &Apache::lonnet::currentdump($self->{'cid'},
1.164 matthew 3137: $self->{'udom'},
1.169 ! matthew 3138: $self->{'uname'});
1.164 matthew 3139: if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
3140: %cachedstores = @tmp;
3141: }
3142: undef @tmp;
3143: #
3144: my @assessdata=();
1.165 matthew 3145: foreach my $row ($self->rows()) {
3146: my $cell = 'A'.$row;
1.164 matthew 3147: my $value = $formulas{$cell};
3148: if(defined($c) && ($c->aborted())) {
3149: last;
3150: }
1.166 matthew 3151: next if ($value =~ /^[!~-]/);
1.164 matthew 3152: my ($usy,$ufn)=split(/__&&&\__/,$value);
3153: @assessdata=$self->exportsheet($self->{'uname'},
3154: $self->{'udom'},
3155: 'assesscalc',$usy,$ufn,$r);
3156: my $index=0;
3157: foreach my $col ('A','B','C','D','E','F','G','H','I','J','K','L','M',
3158: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
3159: if (defined($assessdata[$index])) {
3160: if ($assessdata[$index]=~/\D/) {
3161: $constants{$col.$row}="'".$assessdata[$index]."'";
3162: } else {
3163: $constants{$col.$row}=$assessdata[$index];
3164: }
3165: $formulas{$col.$row}='import' if ($col ne 'A');
3166: }
3167: $index++;
3168: }
1.48 www 3169: }
1.164 matthew 3170: $cachedassess='';
3171: undef %cachedstores;
3172: $self->formulas(\%formulas);
3173: $self->constants(\%constants);
1.48 www 3174: }
1.44 www 3175:
1.164 matthew 3176: # --------------------------------------------------- Load data for one student
1.44 www 3177: #
1.164 matthew 3178: sub loadcourse {
3179: my $self = shift;
3180: my ($r,$c)=@_;
3181: #
3182: my %constants=();
3183: my %formulas=$self->formulas();
3184: #
3185: my $total=0;
1.165 matthew 3186: foreach ($self->rows()) {
3187: $total++ if ($formulas{'A'.$_} !~ /^[!~-]/);
1.164 matthew 3188: }
3189: my $now=0;
3190: my $since=time;
3191: $r->print(<<ENDPOP);
3192: <script>
3193: popwin=open('','popwin','width=400,height=100');
3194: popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
3195: '<h3>Spreadsheet Calculation Progress</h3>'+
3196: '<form name=popremain>'+
3197: '<input type=text size=45 name=remaining value=Starting></form>'+
3198: '</body></html>');
3199: popwin.document.close();
3200: </script>
3201: ENDPOP
3202: $r->rflush();
1.167 matthew 3203: # It would be nice to load in the classlist and assessment info at this
3204: # point, before attacking the student spreadsheets.
1.165 matthew 3205: foreach my $row ($self->rows()) {
1.164 matthew 3206: if(defined($c) && ($c->aborted())) {
3207: last;
3208: }
1.165 matthew 3209: my $cell = 'A'.$row;
1.166 matthew 3210: next if ($formulas{$cell}=~/^[\!\~\-]/);
1.165 matthew 3211: my ($sname,$sdom) = split(':',$formulas{$cell});
1.164 matthew 3212: my $started = time;
3213: my @studentdata=$self->exportsheet($sname,$sdom,'studentcalc',
3214: undef,undef,$r);
3215: undef %userrdatas;
3216: $now++;
3217: $r->print('<script>popwin.document.popremain.remaining.value="'.
3218: $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
3219: ' secs remaining '.(time-$started).' last";</script>');
3220: $r->rflush();
3221: #
3222: my $index=0;
3223: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
3224: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
3225: if (defined($studentdata[$index])) {
3226: my $col=$_;
3227: if ($studentdata[$index]=~/\D/) {
3228: $constants{$col.$row}="'".$studentdata[$index]."'";
3229: } else {
3230: $constants{$col.$row}=$studentdata[$index];
3231: }
3232: unless ($col eq 'A') {
3233: $formulas{$col.$row}='import';
3234: }
3235: }
3236: $index++;
1.78 matthew 3237: }
1.44 www 3238: }
1.164 matthew 3239: $self->formulas(\%formulas);
3240: $self->constants(\%constants);
3241: $r->print('<script>popwin.close()</script>');
3242: $r->rflush();
1.28 www 3243: }
3244:
1.164 matthew 3245: # ------------------------------------------------ Load data for one assessment
1.46 www 3246: #
1.164 matthew 3247: sub loadassessment {
3248: my $self = shift;
3249: my ($r,$c)=@_;
3250:
3251: my $uhome = $self->{'uhome'};
3252: my $uname = $self->{'uname'};
3253: my $udom = $self->{'udom'};
3254: my $symb = $self->{'usymb'};
3255: my $cid = $self->{'cid'};
3256: my $cnum = $self->{'cnum'};
3257: my $cdom = $self->{'cdom'};
3258: my $chome = $self->{'chome'};
3259: my $csec = $self->{'csec'};
1.46 www 3260:
1.164 matthew 3261: my $namespace;
3262: unless ($namespace=$cid) { return ''; }
3263: # Get stored values
3264: my %returnhash=();
3265: if ($cachedassess eq $uname.':'.$udom) {
3266: #
3267: # get data out of the dumped stores
3268: #
3269: if (exists($cachedstores{$symb})) {
3270: %returnhash = %{$cachedstores{$symb}};
3271: } else {
3272: %returnhash = ();
1.78 matthew 3273: }
1.106 matthew 3274: } else {
1.164 matthew 3275: #
3276: # restore individual
3277: #
3278: %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
1.106 matthew 3279: }
3280: #
1.164 matthew 3281: # returnhash now has all stores for this resource
3282: # convert all "_" to "." to be able to use libraries, multiparts, etc
1.136 matthew 3283: #
1.164 matthew 3284: # This is dumb. It is also necessary :(
3285: my @oldkeys=keys %returnhash;
1.136 matthew 3286: #
1.164 matthew 3287: foreach my $name (@oldkeys) {
3288: my $value=$returnhash{$name};
3289: delete $returnhash{$name};
3290: $name=~s/\_/\./g;
3291: $returnhash{$name}=$value;
1.138 matthew 3292: }
1.164 matthew 3293: # initialize coursedata and userdata for this user
3294: undef %courseopt;
3295: undef %useropt;
1.138 matthew 3296:
1.164 matthew 3297: my $userprefix=$uname.'_'.$udom.'_';
1.10 www 3298:
1.164 matthew 3299: unless ($uhome eq 'no_host') {
3300: # Get coursedata
3301: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
3302: my %Tmp = &Apache::lonnet::dump('resourcedata',$cdom,$cnum);
3303: $courserdatas{$cid}=\%Tmp;
3304: $courserdatas{$cid.'.last_cache'}=time;
3305: }
3306: while (my ($name,$value) = each(%{$courserdatas{$cid}})) {
3307: $courseopt{$userprefix.$name}=$value;
3308: }
3309: # Get userdata (if present)
3310: unless ((time-$userrdatas{$uname.'@'.$udom.'.last_cache'})<240) {
3311: my %Tmp = &Apache::lonnet::dump('resourcedata',$udom,$uname);
3312: $userrdatas{$cid} = \%Tmp;
3313: # Most of the time the user does not have a 'resourcedata.db'
3314: # file. We need to cache that we got nothing instead of bothering
3315: # with requesting it every time.
3316: $userrdatas{$uname.'@'.$udom.'.last_cache'}=time;
3317: }
3318: while (my ($name,$value) = each(%{$userrdatas{$cid}})) {
3319: $useropt{$userprefix.$name}=$value;
1.10 www 3320: }
3321: }
1.164 matthew 3322: # now courseopt, useropt initialized for this user and course
3323: # (used by parmval)
3324: #
3325: # Load keys for this assessment only
1.106 matthew 3326: #
1.164 matthew 3327: my %thisassess=();
3328: my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
3329: foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
3330: $thisassess{$_}=1;
3331: }
1.136 matthew 3332: #
1.164 matthew 3333: # Load parameters
1.106 matthew 3334: #
1.164 matthew 3335: my %c=();
3336: if (tie(%parmhash,'GDBM_File',
3337: $self->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
3338: my %f=$self->formulas();
1.165 matthew 3339: foreach my $row ($self->rows()) {
3340: my $cell = 'A'.$row;
1.164 matthew 3341: my $formula = $self->formula($cell);
3342: next if ($formula =~/^[\!\~\-]/);
3343: if ($formula =~ /^parameter/) {
3344: if (defined($thisassess{$formula})) {
3345: my $val = &parmval($formula,$symb,$uname,$udom,$csec);
3346: $c{$cell} = $val;
3347: $c{$formula} = $val;
3348: }
3349: } else {
3350: my $ckey=$formula;
3351: $formula=~s/^stores\_/resource\./;
3352: $formula=~s/\_/\./g;
3353: $c{$cell}=$returnhash{$formula};
3354: $c{$ckey}=$returnhash{$formula};
3355: }
1.139 matthew 3356: }
1.164 matthew 3357: untie(%parmhash);
1.139 matthew 3358: }
1.164 matthew 3359: $self->constants(\%c);
3360: }
3361:
3362:
3363: # =============================================== Update information in a sheet
3364: #
3365: # Add new users or assessments, etc.
3366: #
3367: sub updatesheet {
3368: my $self = shift;
3369: if ($self->{'type'} eq 'classcalc') {
3370: return $self->updateclasssheet();
3371: } else {
3372: return $self->updatestudentassesssheet();
1.139 matthew 3373: }
1.164 matthew 3374: }
3375:
3376: # =================================================== Load the rows for a sheet
3377: #
3378: # Import the data for rows
3379: #
3380: sub loadrows {
3381: my $self = shift;
3382: my ($r)=@_;
3383: my $c = $r->connection;
3384: if ($self->{'type'} eq 'classcalc') {
3385: $self->loadcourse($r,$c);
3386: } elsif ($self->{'type'} eq 'studentcalc') {
3387: $self->loadstudent($r,$c);
1.106 matthew 3388: } else {
1.164 matthew 3389: $self->loadassessment($r,$c);
1.106 matthew 3390: }
1.164 matthew 3391: }
3392:
3393: # ============================================================== Export handler
3394: # exportsheet
3395: # returns the export row for a spreadsheet.
3396: #
3397: sub exportsheet {
3398: my $self = shift;
3399: my ($uname,$udom,$stype,$usymb,$fn,$r)=@_;
3400: my $flag = 0;
3401: $uname = $uname || $self->{'uname'};
3402: $udom = $udom || $self->{'udom'};
3403: $stype = $stype || $self->{'type'};
3404: my @exportarr=();
3405: # This handles the assessment sheets for '_feedback', etc
3406: if (defined($usymb) && ($usymb=~/^\_(\w+)/) &&
3407: (!defined($fn) || $fn eq '')) {
3408: $fn='default_'.$1;
1.106 matthew 3409: }
1.164 matthew 3410: #
3411: # Check if cached
3412: #
3413: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3414: my $found='';
3415: if ($Apache::lonspreadsheet::oldsheets{$key}) {
3416: foreach (split(/___&\___/,$Apache::lonspreadsheet::oldsheets{$key})) {
3417: my ($name,$value)=split(/___=___/,$_);
3418: if ($name eq $fn) {
3419: $found=$value;
3420: }
3421: }
1.106 matthew 3422: }
1.164 matthew 3423: unless ($found) {
3424: &cachedssheets($self,$uname,$udom);
3425: if ($Apache::lonspreadsheet::oldsheets{$key}) {
3426: foreach (split(/___&\___/,$Apache::lonspreadsheet::oldsheets{$key})) {
3427: my ($name,$value)=split(/___=___/,$_);
3428: if ($name eq $fn) {
3429: $found=$value;
3430: }
3431: }
1.104 matthew 3432: }
1.106 matthew 3433: }
1.136 matthew 3434: #
1.164 matthew 3435: # Check if still valid
1.136 matthew 3436: #
1.164 matthew 3437: if ($found) {
3438: if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
3439: $found='';
3440: }
3441: }
3442: if ($found) {
3443: #
3444: # Return what was cached
3445: #
3446: @exportarr=split(/___;___/,$found);
3447: return @exportarr;
1.136 matthew 3448: }
3449: #
1.164 matthew 3450: # Not cached
1.106 matthew 3451: #
1.164 matthew 3452: my $newsheet = Apache::lonspreadsheet::Spreadsheet->new($uname,$udom,
3453: $stype,$usymb);
3454: $newsheet->readsheet($fn);
3455: $newsheet->updatesheet();
3456: $newsheet->loadrows($r);
3457: $newsheet->calcsheet();
3458: @exportarr=$newsheet->exportdata();
3459: ##
3460: ## Store now
3461: ##
1.106 matthew 3462: #
1.164 matthew 3463: # load in the old value
1.106 matthew 3464: #
1.164 matthew 3465: my %currentlystored=();
3466: if ($stype eq 'studentcalc') {
3467: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets',
3468: [$key],
3469: $self->{'cdom'},$self->{'cnum'});
3470: if ($tmp[0]!~/^error/) {
3471: # We only got one key, so we will access it directly.
3472: foreach (split('___&___',$tmp[1])) {
3473: my ($key,$value) = split('___=___',$_);
3474: $key = '' if (! defined($key));
3475: $currentlystored{$key} = $value;
3476: }
3477: }
3478: } else {
3479: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets_'.
3480: $self->{'cid'},[$key],
3481: $self->{'udom'},$self->{'uname'});
3482: if ($tmp[0]!~/^error/) {
3483: # We only got one key, so we will access it directly.
3484: foreach (split('___&___',$tmp[1])) {
3485: my ($key,$value) = split('___=___',$_);
3486: $key = '' if (! defined($key));
3487: $currentlystored{$key} = $value;
3488: }
1.104 matthew 3489: }
1.106 matthew 3490: }
3491: #
1.164 matthew 3492: # Add the new line
3493: #
3494: $currentlystored{$fn}=join('___;___',@exportarr);
1.106 matthew 3495: #
1.164 matthew 3496: # Stick everything back together
1.106 matthew 3497: #
1.164 matthew 3498: my $newstore='';
3499: foreach (keys(%currentlystored)) {
3500: if ($newstore) { $newstore.='___&___'; }
3501: $newstore.=$_.'___=___'.$currentlystored{$_};
1.77 www 3502: }
1.164 matthew 3503: my $now=time;
1.120 matthew 3504: #
1.164 matthew 3505: # Store away the new value
1.134 matthew 3506: #
1.164 matthew 3507: my $timekey = $key.'.time';
3508: if ($stype eq 'studentcalc') {
3509: my $result = &Apache::lonnet::put('nohist_calculatedsheets',
3510: { $key => $newstore,
3511: $timekey => $now },
3512: $self->{'cdom'},
3513: $self->{'cnum'});
3514: } else {
3515: my $result = &Apache::lonnet::put('nohist_calculatedsheets_'.$self->{'cid'},
3516: { $key => $newstore,
3517: $timekey => $now },
3518: $self->{'udom'},
3519: $self->{'uname'});
1.69 www 3520: }
1.164 matthew 3521: return @exportarr;
1.1 www 3522: }
3523:
3524: 1;
1.164 matthew 3525:
1.1 www 3526: __END__
1.154 matthew 3527:
3528:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>