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