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