Diff for /loncom/interface/Attic/lonspreadsheet.pm between versions 1.27 and 1.50

version 1.27, 2001/01/02 12:12:43 version 1.50, 2001/03/21 01:43:22
Line 3 Line 3
 #  #
 # 11/11,11/15,11/27,12/04,12/05,12/06,12/07,  # 11/11,11/15,11/27,12/04,12/05,12/06,12/07,
 # 12/08,12/09,12/11,12/12,12/15,12/16,12/18,12/19,12/30,  # 12/08,12/09,12/11,12/12,12/15,12/16,12/18,12/19,12/30,
 # 01/01/01,02/01 Gerd Kortemeyer  # 01/01/01,02/01,03/01,19/01,20/01,22/01,
   # 03/05,03/08,03/10,03/12,03/13,03/15,03/17,
   # 03/19,03/20 Gerd Kortemeyer
   
 package Apache::lonspreadsheet;  package Apache::lonspreadsheet;
               
 use strict;  use strict;
 use Safe;  use Safe;
 use Safe::Hole;  use Safe::Hole;
Line 17  use GDBM_File; Line 19  use GDBM_File;
 use HTML::TokeParser;  use HTML::TokeParser;
   
 #  #
   # Caches for previously calculated spreadsheets
   #
   
   my %oldsheets;
   my %loadedcaches;
   my %expiredates;
   
   #
   # Cache for stores of an individual user
   #
   
   my $cachedassess;
   my %cachedstores;
   
   #
 # These cache hashes need to be independent of user, resource and course  # These cache hashes need to be independent of user, resource and course
 # (user and course can/should be in the keys)  # (user and course can/should be in the keys)
 #  #
 use vars qw(%spreadsheets %courserdatas %userrdatas %defaultsheets);  
   my %spreadsheets;
   my %courserdatas;
   my %userrdatas;
   my %defaultsheets;
   my %updatedata;
   
 #  #
 # These global hashes are dependent on user, course and resource,   # These global hashes are dependent on user, course and resource, 
Line 30  my %courseopt; Line 52  my %courseopt;
 my %useropt;  my %useropt;
 my %parmhash;  my %parmhash;
   
   # Stuff that only the screen handler can know
   
   my $includedir;
   my $tmpdir;
   
 # =============================================================================  # =============================================================================
 # ===================================== Implements an instance of a spreadsheet  # ===================================== Implements an instance of a spreadsheet
   
 sub initsheet {  sub initsheet {
     my $safeeval = new Safe;      my $safeeval = new Safe(shift);
     my $safehole = new Safe::Hole;      my $safehole = new Safe::Hole;
     $safeeval->permit("entereval");      $safeeval->permit("entereval");
     $safeeval->permit(":base_math");      $safeeval->permit(":base_math");
Line 51  sub initsheet { Line 78  sub initsheet {
 # c: preloaded constants (A-column)  # c: preloaded constants (A-column)
 # rl: row label  # rl: row label
   
 %v=();   undef %v; 
 %t=();  undef %t;
 %f=();  undef %f;
 %c=();  undef %c;
 %rl=();  undef %rl;
   
 $maxrow=0;  $maxrow=0;
 $sheettype='';  $sheettype='';
Line 75  $csec=''; Line 102  $csec='';
 $chome='';  $chome='';
 $cnum='';  $cnum='';
 $cdom='';  $cdom='';
   $cid='';
   $cfn='';
   
 # symb  # symb
   
Line 297  sub sett { Line 326  sub sett {
                     $t{$lb}=~s/\#/$trow/g;                      $t{$lb}=~s/\#/$trow/g;
                     $t{$lb}=~s/\.\.+/\,/g;                      $t{$lb}=~s/\.\.+/\,/g;
                     $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;                      $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
                       $t{$lb}=~s/(^|[^\"\'])\[(\w+)\]/$1\$c\{\'$2\'\}/g;
                 }                  }
       }        }
             } keys %f;              } keys %f;
Line 305  sub sett { Line 335  sub sett {
     } keys %f;      } keys %f;
     map {      map {
  if (($f{$_}) && ($_!~/template\_/)) {   if (($f{$_}) && ($_!~/template\_/)) {
             if ($_=~/^$pattern/) {              my $matches=($_=~/^$pattern(\d+)/);
               if  (($matches) && ($1)) {
         unless ($f{$_}=~/^\!/) {          unless ($f{$_}=~/^\!/) {
     $t{$_}=$c{$_};      $t{$_}=$c{$_};
                 }                  }
Line 313  sub sett { Line 344  sub sett {
        $t{$_}=$f{$_};         $t{$_}=$f{$_};
                $t{$_}=~s/\.\.+/\,/g;                 $t{$_}=~s/\.\.+/\,/g;
                $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;                 $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
                  $t{$_}=~s/(^|[^\"\'])\[([\w\.]+)\]/$1\$c\{\'$2\'\}/g;
             }              }
         }          }
     } keys %f;      } keys %f;
     $t{'A0'}=$f{'A0'};      $t{'A0'}=$f{'A0'};
     $t{'A0'}=~s/\.\.+/\,/g;      $t{'A0'}=~s/\.\.+/\,/g;
     $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;      $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
       $t{'A0'}=~s/(^|[^\"\'])\[([\w\.]+)\]/$1\$c\{\'$2\'\}/g;
 }  }
   
 sub calc {  sub calc {
Line 399  sub outrow { Line 432  sub outrow {
 }  }
   
 sub exportrowa {  sub exportrowa {
     my $rowa='';      my @exportarray=();
     map {      map {
  $rowa.=$v{$_.'0'}."___;___";   $exportarray[$#exportarray+1]=$v{$_.'0'};
     } ('A','B','C','D','E','F','G','H','I','J','K','L','M',      } ('A','B','C','D','E','F','G','H','I','J','K','L','M',
        'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');         'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
     $rowa=~s/\_\_\_\;\_\_\_$//;      return @exportarray;
     return $rowa;  
 }  }
   
 # ------------------------------------------- End of "Inside of the safe space"  # ------------------------------------------- End of "Inside of the safe space"
Line 417  ENDDEFS Line 449  ENDDEFS
 # ------------------------------------------------ Add or change formula values  # ------------------------------------------------ Add or change formula values
   
 sub setformulas {  sub setformulas {
     my ($safeeval,@f)=@_;      my ($safeeval,%f)=@_;
     $safeeval->reval('%f='."('".join("','",@f)."');");      %{$safeeval->varglob('f')}=%f;
 }  }
   
 # ------------------------------------------------ Add or change formula values  # ------------------------------------------------ Add or change formula values
   
 sub setconstants {  sub setconstants {
     my ($safeeval,@c)=@_;      my ($safeeval,%c)=@_;
     $safeeval->reval('%c='."('".join("','",@c)."');");      %{$safeeval->varglob('c')}=%c;
 }  }
   
 # ------------------------------------------------ Add or change formula values  # ------------------------------------------------ Add or change formula values
   
 sub setrowlabels {  sub setrowlabels {
     my ($safeeval,@rl)=@_;      my ($safeeval,%rl)=@_;
     $safeeval->reval('%rl='."('".join("','",@rl)."');");      %{$safeeval->varglob('rl')}=%rl;
 }  }
   
 # ------------------------------------------------------- Calculate spreadsheet  # ------------------------------------------------------- Calculate spreadsheet
Line 453  sub getvalues { Line 485  sub getvalues {
   
 sub getformulas {  sub getformulas {
     my $safeeval=shift;      my $safeeval=shift;
     return $safeeval->reval('%f');      return %{$safeeval->varglob('f')};
 }  
   
 # -------------------------------------------------------------------- Set type  
   
 sub settype {  
     my ($safeeval,$type)=@_;  
     $safeeval->reval('$sheettype="'.$type.'";');  
 }  }
   
 # -------------------------------------------------------------------- Get type  # -------------------------------------------------------------------- Get type
Line 498  sub getfilename { Line 523  sub getfilename {
     return $safeeval->reval('$filename');      return $safeeval->reval('$filename');
 }  }
   
   # --------------------------------------------------------------- Get course ID
   
   sub getcid {
       my $safeeval=shift;
       return $safeeval->reval('$cid');
   }
   
   # --------------------------------------------------------- Get course filename
   
   sub getcfn {
       my $safeeval=shift;
       return $safeeval->reval('$cfn');
   }
   
 # ----------------------------------------------------------- Get course number  # ----------------------------------------------------------- Get course number
   
 sub getcnum {  sub getcnum {
Line 556  sub getusymb { Line 595  sub getusymb {
   
 # ------------------------------------------------------------- Export of A-row  # ------------------------------------------------------------- Export of A-row
   
 sub exportrow {  sub exportdata {
     my $safeeval=shift;      my $safeeval=shift;
     return $safeeval->reval('&exportrowa()');      return $safeeval->reval('&exportrowa()');
 }  }
Line 684  sub readsheet { Line 723  sub readsheet {
   my ($safeeval,$fn)=@_;    my ($safeeval,$fn)=@_;
   my $stype=&gettype($safeeval);    my $stype=&gettype($safeeval);
   my $cnum=&getcnum($safeeval);    my $cnum=&getcnum($safeeval);
     my $cdom=&getcdom($safeeval);
     my $chome=&getchome($safeeval);
   
 # --------- There is no filename. Look for defaults in course and global, cache  # --------- There is no filename. Look for defaults in course and global, cache
   
   unless($fn) {    unless($fn) {
       unless ($fn=$defaultsheets{$cnum.'_'.$stype}) {        unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
          $fn=&Apache::lonnet::reply('get:'.           $fn=&Apache::lonnet::reply('get:'.$cdom.':'.$cnum.
                 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.                                      ':environment:spreadsheet_default_'.$stype,
                 $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.                                      $chome);
                 ':environment:spreadsheet_default_'.&gettype($safeeval),  
                      $ENV{'course.'.$ENV{'request.course.id'}.'.home'});  
          unless (($fn) && ($fn!~/^error\:/)) {           unless (($fn) && ($fn!~/^error\:/)) {
      $fn='default_'.$stype;       $fn='default_'.$stype;
          }           }
          $defaultsheets{$cnum.'_'.$stype}=$fn;            $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
       }        }
   }    }
   
Line 707  sub readsheet { Line 746  sub readsheet {
   
 # ------------------------------------------------------ see if sheet is cached  # ------------------------------------------------------ see if sheet is cached
   my $fstring='';    my $fstring='';
   if ($fstring=$spreadsheets{$cnum.'_'.$stype.'_'.$fn}) {    if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
       &setformulas($sheetone,split(/\_\_\_\;\_\_\_/,$fstring));        &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
   } else {    } else {
   
 # ---------------------------------------------------- Not cached, need to read  # ---------------------------------------------------- Not cached, need to read
Line 719  sub readsheet { Line 758  sub readsheet {
  my $sheetxml='';   my $sheetxml='';
        {         {
          my $fh;           my $fh;
          if ($fh=Apache::File->new($r->dir_config('lonIncludes').           if ($fh=Apache::File->new($includedir.
                          '/default.'.&gettype($safeeval))) {                           '/default.'.&gettype($safeeval))) {
                $sheetxml=join('',<$fh>);                 $sheetxml=join('',<$fh>);
           }            }
Line 739  sub readsheet { Line 778  sub readsheet {
           }            }
         }          }
       } else {        } else {
         my $sheet='';            my $sheet='';
         my $reply=&Apache::lonnet::reply('dump:'.            my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.':'.$fn,
               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.                                           $chome);
               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.':'.$fn,  
               $ENV{'course.'.$ENV{'request.course.id'}.'.home'});  
           unless ($reply=~/^error\:/) {            unless ($reply=~/^error\:/) {
              $sheet=$reply;               $sheet=$reply;
   }    }
Line 754  sub readsheet { Line 791  sub readsheet {
           } split(/\&/,$sheet);            } split(/\&/,$sheet);
        }         }
 # --------------------------------------------------------------- Cache and set  # --------------------------------------------------------------- Cache and set
        $spreadsheets{$cnum.'_'.$stype.'_'.$fn}=join('___;___',%f);                $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
        &setformulas($safeeval,%f);         &setformulas($safeeval,%f);
     }      }
 }  }
   
   # -------------------------------------------------------- Make new spreadsheet
   
   sub makenewsheet {
       my ($uname,$udom,$stype,$usymb)=@_;
       my $safeeval=initsheet($stype);
       $safeeval->reval(
          '$uname="'.$uname.
         '";$udom="'.$udom.
         '";$uhome="'.&Apache::lonnet::homeserver($uname,$udom).
         '";$sheettype="'.$stype.
         '";$usymb="'.$usymb.
         '";$csec="'.&Apache::lonnet::usection($udom,$uname,
                                               $ENV{'request.course.id'}).
         '";$cid="'.$ENV{'request.course.id'}.
         '";$cfn="'.$ENV{'request.course.fn'}.
         '";$cnum="'.$ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
         '";$cdom="'.$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
         '";$chome="'.$ENV{'course.'.$ENV{'request.course.id'}.'.home'}.'";');
       return $safeeval;
   }
   
 # ------------------------------------------------------------ Save spreadsheet  # ------------------------------------------------------------ Save spreadsheet
   
 sub writesheet {  sub writesheet {
   my $safeeval=shift;    my ($safeeval,$makedef)=@_;
   if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {    my $cid=&getcid($safeeval);
     if (&Apache::lonnet::allowed('opa',$cid)) {
     my %f=&getformulas($safeeval);      my %f=&getformulas($safeeval);
       my $stype=&gettype($safeeval);
       my $cnum=&getcnum($safeeval);
       my $cdom=&getcdom($safeeval);
       my $chome=&getchome($safeeval);
       my $fn=&getfilename($safeeval);
   
   # ------------------------------------------------------------- Cache new sheet
       $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);    
   # ----------------------------------------------------------------- Write sheet
     my $sheetdata='';      my $sheetdata='';
     map {      map {
        $sheetdata.=&Apache::lonnet::escape($_).'='.         $sheetdata.=&Apache::lonnet::escape($_).'='.
    &Apache::lonnet::escape($f{$_}).'&';     &Apache::lonnet::escape($f{$_}).'&';
     } keys %f;      } keys %f;
     $sheetdata=~s/\&$//;      $sheetdata=~s/\&$//;
     my $reply=&Apache::lonnet::reply('put:'.      my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.                $sheetdata,$chome);
               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.':'.  
               &getfilename($safeeval).':'.  
               $sheetdata,  
               $ENV{'course.'.$ENV{'request.course.id'}.'.home'});  
     if ($reply eq 'ok') {      if ($reply eq 'ok') {
           return &Apache::lonnet::reply('put:'.            $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.                $stype.'_spreadsheets:'.
               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.':'.                &Apache::lonnet::escape($fn).'='.$ENV{'user.name'},
               &gettype($safeeval).'_spreadsheets:'.                $chome);
               &Apache::lonnet::escape(&getfilename($safeeval)).'='.            if ($reply eq 'ok') {
               $ENV{'user.name'},                if ($makedef) { 
               $ENV{'course.'.$ENV{'request.course.id'}.'.home'});                      return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
                                   ':environment:spreadsheet_default_'.$stype.'='.
                                   &Apache::lonnet::escape($fn),
                                   $chome);
         } else {
     return $reply;
            }
      } else {
          return $reply;
              }
       } else {        } else {
   return $reply;    return $reply;
       }        }
Line 793  sub writesheet { Line 866  sub writesheet {
 }  }
   
 # ----------------------------------------------- Make a temp copy of the sheet  # ----------------------------------------------- Make a temp copy of the sheet
   # "Modified workcopy" - interactive only
   #
   
 sub tmpwrite {  sub tmpwrite {
     my ($safeeval,$tmpdir,$symb)=@_;      my $safeeval=shift;
     my $fn=$uname.'_'.$udom.'_spreadsheet_'.$symb.'_'.&getfilename($safeeval);      my $fn=$ENV{'user.name'}.'_'.
              $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
              &getfilename($safeeval);
     $fn=~s/\W/\_/g;      $fn=~s/\W/\_/g;
     $fn=$tmpdir.$fn.'.tmp';      $fn=$tmpdir.$fn.'.tmp';
     my $fh;      my $fh;
Line 808  sub tmpwrite { Line 885  sub tmpwrite {
 # ---------------------------------------------------------- Read the temp copy  # ---------------------------------------------------------- Read the temp copy
   
 sub tmpread {  sub tmpread {
     my ($safeeval,$tmpdir,$symb,$nfield,$nform)=@_;      my ($safeeval,$nfield,$nform)=@_;
     my $fn=$uname.'_'.$udom.'_spreadsheet_'.$symb.'_'.&getfilename($safeeval);      my $fn=$ENV{'user.name'}.'_'.
              $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
              &getfilename($safeeval);
     $fn=~s/\W/\_/g;      $fn=~s/\W/\_/g;
     $fn=$tmpdir.$fn.'.tmp';      $fn=$tmpdir.$fn.'.tmp';
     my $fh;      my $fh;
Line 827  sub tmpread { Line 906  sub tmpread {
     &setformulas($safeeval,%fo);      &setformulas($safeeval,%fo);
 }  }
   
 # --------------------------------------------------------------- Read metadata  
   
 sub readmeta {  
     my $fn=shift;  
     unless ($fn=~/\.meta$/) { $fn.='meta'; }  
     my $content;  
     my %returnhash=();  
     {  
       my $fh=Apache::File->new($fn);  
       $content=join('',<$fh>);  
     }  
    my $parser=HTML::TokeParser->new(\$content);  
    my $token;  
    while ($token=$parser->get_token) {  
       if ($token->[0] eq 'S') {  
          my $entry=$token->[1];  
          if (($entry eq 'stores') || ($entry eq 'parameter')) {  
              my $unikey=$entry;  
              $unikey.='_'.$token->[2]->{'part'};   
              $unikey.='_'.$token->[2]->{'name'};   
              $returnhash{$unikey}=$token->[2]->{'display'};  
          }  
      }  
   }  
     return %returnhash;  
 }  
   
 # ================================================================== Parameters  # ================================================================== Parameters
 # -------------------------------------------- Figure out a cascading parameter  # -------------------------------------------- Figure out a cascading parameter
   #
   # For this function to work
   #
   # * parmhash needs to be tied
   # * courseopt and useropt need to be initialized for this user and course
   #
   
 sub parmval {  sub parmval {
     my ($what,$symb)=@_;      my ($what,$safeeval)=@_;
       my $cid=&getcid($safeeval);
       my $csec=&getcsec($safeeval);
       my $uname=&getuname($safeeval);
       my $udom=&getudom($safeeval);
       my $symb=&getusymb($safeeval);
   
     unless ($symb) { return ''; }      unless ($symb) { return ''; }
     my $result='';      my $result='';
Line 871  sub parmval { Line 934  sub parmval {
   
        my $symbparm=$symb.'.'.$what;         my $symbparm=$symb.'.'.$what;
        my $mapparm=$mapname.'___(all).'.$what;         my $mapparm=$mapname.'___(all).'.$what;
          my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
   
        my $seclevel=         my $seclevel=
             $ENV{'request.course.id'}.'.['.              $usercourseprefix.'.['.
  $csec.'].'.$what;   $csec.'].'.$what;
        my $seclevelr=         my $seclevelr=
             $ENV{'request.course.id'}.'.['.              $usercourseprefix.'.['.
  $csec.'].'.$symbparm;   $csec.'].'.$symbparm;
        my $seclevelm=         my $seclevelm=
             $ENV{'request.course.id'}.'.['.              $usercourseprefix.'.['.
  $csec.'].'.$mapparm;   $csec.'].'.$mapparm;
   
        my $courselevel=         my $courselevel=
             $ENV{'request.course.id'}.'.'.$what;              $usercourseprefix.'.'.$what;
        my $courselevelr=         my $courselevelr=
             $ENV{'request.course.id'}.'.'.$symbparm;              $usercourseprefix.'.'.$symbparm;
        my $courselevelm=         my $courselevelm=
             $ENV{'request.course.id'}.'.'.$mapparm;              $usercourseprefix.'.'.$mapparm;
   
 # ---------------------------------------------------------- fourth, check user  # ---------------------------------------------------------- fourth, check user
               
Line 932  sub parmval { Line 996  sub parmval {
   
 # ---------------------------------------------- Update rows for course listing  # ---------------------------------------------- Update rows for course listing
   
 sub updatestudentrows {  sub updateclasssheet {
     my $safeeval=shift;      my $safeeval=shift;
     my $cid=$ENV{'request.course.id'};      my $cnum=&getcnum($safeeval);
       my $cdom=&getcdom($safeeval);
       my $cid=&getcid($safeeval);
       my $chome=&getchome($safeeval);
   
   # ---------------------------------------------- Read class list and row labels
   
     my $classlst=&Apache::lonnet::reply      my $classlst=&Apache::lonnet::reply
                  ('dump:'.$ENV{'course.'.$cid.'.domain'}.':'.                                   ('dump:'.$cdom.':'.$cnum.':classlist',$chome);
                   $ENV{'course.'.$cid.'.num'}.':classlist',  
                   $ENV{'course.'.$cid.'.home'});  
     my %currentlist=();      my %currentlist=();
     my $now=time;      my $now=time;
     unless ($classlst=~/^error\:/) {      unless ($classlst=~/^error\:/) {
Line 950  sub updatestudentrows { Line 1018  sub updatestudentrows {
             if ($active) {              if ($active) {
                 my $rowlabel='';                  my $rowlabel='';
                 $name=&Apache::lonnet::unescape($name);                  $name=&Apache::lonnet::unescape($name);
                 my ($cname,$cdom)=split(/\:/,$name);                  my ($sname,$sdom)=split(/\:/,$name);
                 my $csec=                  my $ssec=&Apache::lonnet::usection($sdom,$sname,$cid);
              &Apache::lonnet::usection($cdom,$cname,$ENV{'request.course.id'});                  if ($ssec==-1) {
                 if ($csec==-1) {  
                     $rowlabel='<font color=red>Data not available: '.$name.                      $rowlabel='<font color=red>Data not available: '.$name.
       '</font>';        '</font>';
                 } else {                  } else {
                     my %reply=&Apache::lonnet::idrget($cdom,$cname);                      my %reply=&Apache::lonnet::idrget($sdom,$sname);
                     my $reply=&Apache::lonnet::reply('get:'.$cdom.':'.$cname.                      my $reply=&Apache::lonnet::reply('get:'.$sdom.':'.$sname.
       ':environment:firstname&middlename&lastname&generation',        ':environment:firstname&middlename&lastname&generation',
                       &Apache::lonnet::homeserver($cname,$cdom));                        &Apache::lonnet::homeserver($sname,$sdom));
                     $rowlabel=$csec.'&nbsp;'.$reply{$cname}.'<br>';                      $rowlabel='<a href="/adm/studentcalc?uname='.$sname.
                                 '&udom='.$sdom.'">'.
                                 $ssec.'&nbsp;'.$reply{$sname}.'<br>';
                     map {                      map {
                         $rowlabel.=&Apache::lonnet::unescape($_).' ';                          $rowlabel.=&Apache::lonnet::unescape($_).' ';
                     } split(/\&/,$reply);                      } split(/\&/,$reply);
                       $rowlabel.='</a>';
                 }                  }
                  
  $currentlist{&Apache::lonnet::unescape($name)}=$rowlabel;   $currentlist{&Apache::lonnet::unescape($name)}=$rowlabel;
             }              }
         } split(/\&/,$classlst);          } split(/\&/,$classlst);
Line 1010  sub updatestudentrows { Line 1079  sub updatestudentrows {
         return 'Could not access course data';          return 'Could not access course data';
     }      }
 }  }
 # ----------------------------------------------------------------- Update rows  
   
 sub updaterows {  # ----------------------------------- Update rows for student and assess sheets
   
   sub updatestudentassesssheet {
     my $safeeval=shift;      my $safeeval=shift;
     my %bighash;      my %bighash;
       my $stype=&gettype($safeeval);
       my %current=();
       unless ($updatedata{$ENV{'request.course.fn'}.'_'.$stype}) {
 # -------------------------------------------------------------------- Tie hash  # -------------------------------------------------------------------- Tie hash
       if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',        if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
                        &GDBM_READER,0640)) {                         &GDBM_READER,0640)) {
Line 1023  sub updaterows { Line 1096  sub updaterows {
  my %allkeys=();   my %allkeys=();
         my %allassess=();          my %allassess=();
   
         my $stype=&gettype($safeeval);          my $adduserstr='';
           if ((&getuname($safeeval) ne $ENV{'user.name'}) ||
               (&getudom($safeeval) ne $ENV{'user.domain'})) {
               $adduserstr='&uname='.&getuname($safeeval).
    '&udom='.&getudom($safeeval);
           }
   
         map {          map {
     if ($_=~/^src\_(\d+)\.(\d+)$/) {      if ($_=~/^src\_(\d+)\.(\d+)$/) {
Line 1036  sub updaterows { Line 1114  sub updaterows {
                      &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).                       &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
     '___'.$resid.'___'.      '___'.$resid.'___'.
     &Apache::lonnet::declutter($srcf);      &Apache::lonnet::declutter($srcf);
  $allassess{$symb}=$bighash{'title_'.$id};   $allassess{$symb}=
               '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
                        $bighash{'title_'.$id}.'</a>';
                  if ($stype eq 'assesscalc') {                   if ($stype eq 'assesscalc') {
                    map {                     map {
                        if (($_=~/^stores\_(.*)/) || ($_=~/^parameter\_(.*)/)) {                         if (($_=~/^stores\_(.*)/) || ($_=~/^parameter\_(.*)/)) {
Line 1045  sub updaterows { Line 1124  sub updaterows {
                           my $display=                            my $display=
       &Apache::lonnet::metadata($srcf,$key.'.display');        &Apache::lonnet::metadata($srcf,$key.'.display');
                           unless ($display) {                            unless ($display) {
                               $display=                                $display.=
          &Apache::lonnet::metadata($srcf,$key.'.name');           &Apache::lonnet::metadata($srcf,$key.'.name');
                           }                            }
                             $display.='<br>'.$key;
                           $allkeys{$key}=$display;                            $allkeys{$key}=$display;
        }         }
                    } split(/\,/,&Apache::lonnet::metadata($srcf,'keys'));                     } split(/\,/,&Apache::lonnet::metadata($srcf,'keys'));
Line 1061  sub updaterows { Line 1141  sub updaterows {
 # %allkeys has a list of storage and parameter displays by unikey  # %allkeys has a list of storage and parameter displays by unikey
 # %allassess has a list of all resource displays by symb  # %allassess has a list of all resource displays by symb
 #  #
 # -------------------- Find discrepancies between the course row table and this  
 #  
         my %f=&getformulas($safeeval);  
         my $changed=0;  
   
         my %current=();  
         if ($stype eq 'assesscalc') {          if ($stype eq 'assesscalc') {
     %current=%allkeys;      %current=%allkeys;
         } elsif ($stype eq 'studentcalc') {          } elsif ($stype eq 'studentcalc') {
             %current=%allassess;              %current=%allassess;
         }          }
           $updatedata{$ENV{'request.course.fn'}.'_'.$stype}=
       join('___;___',%current);
       } else {
           return 'Could not access course data';
       }
   # ------------------------------------------------------ Get current from cache
       } else {
           %current=split(/\_\_\_\;\_\_\_/,
          $updatedata{$ENV{'request.course.fn'}.'_'.$stype});
       }
   # -------------------- Find discrepancies between the course row table and this
   #
           my %f=&getformulas($safeeval);
           my $changed=0;
   
         my $maxrow=0;          my $maxrow=0;
         my %existing=();          my %existing=();
Line 1097  sub updaterows { Line 1186  sub updaterows {
                 $f{'A'.$maxrow}=$_;                  $f{'A'.$maxrow}=$_;
             }              }
         } keys %current;                  } keys %current;        
            
         if ($changed) { &setformulas($safeeval,%f); }          if ($changed) { &setformulas($safeeval,%f); }
   
         &setmaxrow($safeeval,$maxrow);          &setmaxrow($safeeval,$maxrow);
         &setrowlabels($safeeval,%current);          &setrowlabels($safeeval,%current);
    
     } else {          undef %current;
         return 'Could not access course data';          undef %existing;
     }  
 }  }
   
 # ------------------------------------------------ Load data for one assessment  # ------------------------------------------------ Load data for one assessment
   
 sub rowazstudent {  sub loadstudent {
     my $safeeval=shift;      my $safeeval=shift;
     my %c=();      my %c=();
     my %f=&getformulas($safeeval);      my %f=&getformulas($safeeval);
       $cachedassess=&getuname($safeeval).':'.&getudom($safeeval);
       %cachedstores=();
       {
         my $reply=&Apache::lonnet::reply('dump:'.&getudom($safeeval).':'.
                                                  &getuname($safeeval).':'.
                                                  &getcid($safeeval),
                                                  &getuhome($safeeval));
         unless ($reply=~/^error\:/) {
            map {
               my ($name,$value)=split(/\=/,$_);
               $cachedstores{&Apache::lonnet::unescape($name)}=
                     &Apache::lonnet::unescape($value);
            } split(/\&/,$reply);
         }
       }
       my @assessdata=();
     map {      map {
  if ($_=~/^A(\d+)/) {   if ($_=~/^A(\d+)/) {
    my $row=$1;     my $row=$1;
            unless ($f{$_}=~/^\!/) {             unless (($f{$_}=~/^\!/) || ($row==0)) {
               my @assessdata=split(/\_\_\_\;\_\_\_/,        @assessdata=&exportsheet(&getuname($safeeval),
                              &Apache::lonnet::ssi(                                         &getudom($safeeval),
                        '/adm/assesscalc',('utarget' => 'export',                                         'assesscalc',$f{$_});
                                           'uname'   => $uname,  
                                           'udom'    => $udom,  
                   'usymb'   => $f{$_})));  
               my $index=0;                my $index=0;
               map {                map {
                   if ($assessdata[$index]) {                    if ($assessdata[$index]) {
      $c{$_.$row}=$assessdata[$index];       my $col=$_;
                      unless ($_ eq 'A') {        if ($assessdata[$index]=~/\D/) {
  $f{$_.$row}='import';                           $c{$col.$row}="'".$assessdata[$index]."'";
         } else {
            $c{$col.$row}=$assessdata[$index];
        }
                        unless ($col eq 'A') { 
    $f{$col.$row}='import';
                      }                       }
   }    }
                   $index++;                    $index++;
Line 1138  sub rowazstudent { Line 1244  sub rowazstudent {
    }     }
         }          }
     } keys %f;      } keys %f;
       $cachedassess='';
       undef %cachedstores;
     &setformulas($safeeval,%f);      &setformulas($safeeval,%f);
     &setconstants($safeeval,%c);      &setconstants($safeeval,%c);
 }  }
   
 # --------------------------------------------------- Load data for one student  # --------------------------------------------------- Load data for one student
   
 sub rowazclass {  sub loadcourse {
     my $safeeval=shift;      my ($safeeval,$r)=@_;
     my %c=();      my %c=();
     my %f=&getformulas($safeeval);      my %f=&getformulas($safeeval);
       my $total=0;
       map {
    if ($_=~/^A(\d+)/) {
       unless ($f{$_}=~/^\!/) { $total++; }
           }
       } keys %f;
       my $now=0;
       my $since=time;
       $r->print(<<ENDPOP);
   <script>
       popwin=open('','popwin','width=400,height=100');
       popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
         '<h3>Spreadsheet Calculation Progress</h3>'+
         '<form name=popremain>'+
         '<input type=text size=35 name=remaining value=Starting></form>'+
         '</body></html>');
       popwin.document.close();
   </script>
   ENDPOP
       $r->rflush();
     map {      map {
  if ($_=~/^A(\d+)/) {   if ($_=~/^A(\d+)/) {
    my $row=$1;     my $row=$1;
            unless ($f{$_}=~/^\!/) {             unless (($f{$_}=~/^\!/)  || ($row==0)) {
       my ($tname,$tdom)=split(/\:/,$_);        my @studentdata=&exportsheet(split(/\:/,$f{$_}),
               my @assessdata=split(/\_\_\_\;\_\_\_/,                                             'studentcalc');
                              &Apache::lonnet::ssi(                undef %userrdatas;
                       '/adm/studentcalc',('utarget' => 'export',                $now++;
                                           'uname'   => $tname,                $r->print('<script>popwin.document.popremain.remaining.value="'.
                                           'udom'    => $tdom)));                    $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
                           ' secs remaining";</script>');
                 $r->rflush(); 
   
               my $index=0;                my $index=0;
               map {                map {
                   if ($assessdata[$index]) {                    if ($studentdata[$index]) {
      $c{$_.$row}=$assessdata[$index];       my $col=$_;
                      unless ($_ eq 'A') {        if ($studentdata[$index]=~/\D/) {
  $f{$_.$row}='import';                           $c{$col.$row}="'".$studentdata[$index]."'";
         } else {
            $c{$col.$row}=$studentdata[$index];
        }
                        unless ($col eq 'A') { 
    $f{$col.$row}='import';
                      }                       }
   }    }
                   $index++;                    $index++;
Line 1174  sub rowazclass { Line 1310  sub rowazclass {
     } keys %f;      } keys %f;
     &setformulas($safeeval,%f);      &setformulas($safeeval,%f);
     &setconstants($safeeval,%c);      &setconstants($safeeval,%c);
       $r->print('<script>popwin.close()</script>');
       $r->rflush(); 
 }  }
   
 # ------------------------------------------------ Load data for one assessment  # ------------------------------------------------ Load data for one assessment
   
 sub rowaassess {  sub loadassessment {
     my ($safeeval,$symb)=@_;      my $safeeval=shift;
     my $uhome=&Apache::lonnet::homeserver($uname,$udom);  
       my $uhome=&getuhome($safeeval);
       my $uname=&getuname($safeeval);
       my $udom=&getudom($safeeval);
       my $symb=&getusymb($safeeval);
       my $cid=&getcid($safeeval);
       my $cnum=&getcnum($safeeval);
       my $cdom=&getcdom($safeeval);
       my $chome=&getchome($safeeval);
   
     my $namespace;      my $namespace;
     unless ($namespace=$ENV{'request.course.id'}) { return ''; }      unless ($namespace=$cid) { return ''; }
   
 # ----------------------------------------------------------- Get stored values  # ----------------------------------------------------------- Get stored values
   
      my %returnhash=();
   
      if ($cachedassess eq $uname.':'.$udom) {
   #
   # get data out of the dumped stores
   # 
   
          my $version=$cachedstores{'version:'.$symb};
          my $scope;
          for ($scope=1;$scope<=$version;$scope++) {
              map {
                  $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
              } split(/\:/,$cachedstores{$scope.':keys:'.$symb}); 
          }
   
      } else {
   #
   # restore individual
   #
   
     my $answer=&Apache::lonnet::reply(      my $answer=&Apache::lonnet::reply(
        "restore:$udom:$uname:".         "restore:$udom:$uname:".
        &Apache::lonnet::escape($namespace).":".         &Apache::lonnet::escape($namespace).":".
        &Apache::lonnet::escape($symb),$uhome);         &Apache::lonnet::escape($symb),$uhome);
     my %returnhash=();  
     map {      map {
  my ($name,$value)=split(/\=/,$_);   my ($name,$value)=split(/\=/,$_);
         $returnhash{&Apache::lonnet::unescape($name)}=          $returnhash{&Apache::lonnet::unescape($name)}=
Line 1201  sub rowaassess { Line 1368  sub rowaassess {
           $returnhash{$_}=$returnhash{$version.':'.$_};            $returnhash{$_}=$returnhash{$version.':'.$_};
        } split(/\:/,$returnhash{$version.':keys'});         } split(/\:/,$returnhash{$version.':keys'});
     }      }
      }
 # ----------------------------- returnhash now has all stores for this resource  # ----------------------------- returnhash now has all stores for this resource
   
 # ---------------------------- initialize coursedata and userdata for this user  # ---------------------------- initialize coursedata and userdata for this user
     %courseopt=();      undef %courseopt;
     %useropt=();      undef %useropt;
     my $uhome=&Apache::lonnet::homeserver($uname,$udom);  
       my $userprefix=$uname.'_'.$udom.'_';
   
     unless ($uhome eq 'no_host') {       unless ($uhome eq 'no_host') { 
 # -------------------------------------------------------------- Get coursedata  # -------------------------------------------------------------- Get coursedata
       unless        unless
         ((time-$courserdatas{$ENV{'request.course.id'}.'.last_cache'})<120) {          ((time-$courserdatas{$cid.'.last_cache'})<240) {
          my $reply=&Apache::lonnet::reply('dump:'.           my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
               $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.                ':resourcedata',$chome);
               $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.':resourcedata',  
               $ENV{'course.'.$ENV{'request.course.id'}.'.home'});  
          if ($reply!~/^error\:/) {           if ($reply!~/^error\:/) {
             $courserdatas{$ENV{'request.course.id'}}=$reply;              $courserdatas{$cid}=$reply;
             $courserdatas{$ENV{'request.course.id'}.'.last_cache'}=time;              $courserdatas{$cid.'.last_cache'}=time;
          }           }
       }        }
       map {        map {
          my ($name,$value)=split(/\=/,$_);           my ($name,$value)=split(/\=/,$_);
          $courseopt{&Apache::lonnet::unescape($name)}=           $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
                     &Apache::lonnet::unescape($value);                        &Apache::lonnet::unescape($value);  
       } split(/\&/,$courserdatas{$ENV{'request.course.id'}});        } split(/\&/,$courserdatas{$cid});
 # --------------------------------------------------- Get userdata (if present)  # --------------------------------------------------- Get userdata (if present)
       unless        unless
         ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<120) {          ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
          my $reply=           my $reply=
        &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);         &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
          if ($reply!~/^error\:/) {           if ($reply!~/^error\:/) {
Line 1237  sub rowaassess { Line 1405  sub rowaassess {
       }        }
       map {        map {
          my ($name,$value)=split(/\=/,$_);           my ($name,$value)=split(/\=/,$_);
          $useropt{&Apache::lonnet::unescape($name)}=           $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
           &Apache::lonnet::unescape($value);            &Apache::lonnet::unescape($value);
       } split(/\&/,$userrdatas{$uname.'___'.$udom});        } split(/\&/,$userrdatas{$uname.'___'.$udom});
    }      }
 # -- now courseopt, useropt initialized for this user and course (used parmval)  # ----------------- now courseopt, useropt initialized for this user and course
   # (used by parmval)
   
     my %c=();     my %c=();
   
      if (tie(%parmhash,'GDBM_File',
              &getcfn($safeeval).'_parms.db',&GDBM_READER,0640)) {
     my %f=&getformulas($safeeval);      my %f=&getformulas($safeeval);
     map {      map {
  if ($_=~/^A/) {   if ($_=~/^A/) {
             unless ($f{$_}=~/^\!/) {              unless ($f{$_}=~/^\!/) {
         if ($f{$_}=~/^parameter/) {          if ($f{$_}=~/^parameter/) {
           $c{$_}=&parmval($f{$_},$symb);                    my $val=&parmval($f{$_},$safeeval);
                     $c{$_}=$val;
                     $c{$f{$_}}=$val;
        } else {         } else {
   my $key=$f{$_};    my $key=$f{$_};
                     my $ckey=$key;
                   $key=~s/^stores\_/resource\./;                    $key=~s/^stores\_/resource\./;
                   $key=~s/\_/\./;                    $key=~s/\_/\./;
            $c{$_}=$returnhash{$key};             $c{$_}=$returnhash{$key};
                     $c{$ckey}=$returnhash{$key};
        }         }
    }     }
         }          }
     } keys %f;      } keys %f;
       untie(%parmhash);
     &setconstants($safeeval,%c);     }
      &setconstants($safeeval,%c);
 }  }
   
 # --------------------------------------------------------- Various form fields  # --------------------------------------------------------- Various form fields
Line 1287  sub selectbox { Line 1464  sub selectbox {
     return $selout.'</select>';      return $selout.'</select>';
 }  }
   
   # =============================================== Update information in a sheet
   #
   # Add new users or assessments, etc.
   #
   
   sub updatesheet {
       my $safeeval=shift;
       my $stype=&gettype($safeeval);
       if ($stype eq 'classcalc') {
    return &updateclasssheet($safeeval);
       } else {
           return &updatestudentassesssheet($safeeval);
       }
   }
   
   # =================================================== Load the rows for a sheet
   #
   # Import the data for rows
   #
   
   sub loadrows {
       my ($safeeval,$r)=@_;
       my $stype=&gettype($safeeval);
       if ($stype eq 'classcalc') {
    &loadcourse($safeeval,$r);
       } elsif ($stype eq 'studentcalc') {
           &loadstudent($safeeval);
       } else {
           &loadassessment($safeeval);
       }
   }
   
   # ======================================================= Forced recalculation?
   
   sub checkthis {
       my ($keyname,$time)=@_;
       return ($time<$expiredates{$keyname});
   }
   sub forcedrecalc {
       my ($uname,$udom,$stype,$usymb)=@_;
       my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
       my $time=$oldsheets{$key.'.time'};
       unless ($time) { return 1; }
       if ($stype eq 'assesscalc') {
           my $map=(split(/\_\_\_/,$usymb))[0];
           if (&checkthis('::assesscalc:',$time) ||
               &checkthis('::assesscalc:'.$map,$time) ||
               &checkthis('::assesscalc:'.$usymb,$time) ||
               &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
               &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
               &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
               return 1;
           } 
       } else {
           if (&checkthis('::studentcalc:',$time) || 
               &checkthis($uname.':'.$udom.':studencalc:',$time)) {
       return 1;
           }
       }
       return 0; 
   }
   
   # ============================================================== Export handler
   #
   # Non-interactive call from with program
   #
   
   sub exportsheet {
    my ($uname,$udom,$stype,$usymb,$fn)=@_;
    my @exportarr=();
   #
   # Check if cached
   #
   
    my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
    my $found='';
   
    if ($oldsheets{$key}) {
        map {
            my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
            if ($name eq $fn) {
        $found=$value;
            }
        } split(/\_\_\_\&\_\_\_/,$oldsheets{$key});
    }
   
    unless ($found) {
        &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
        if ($oldsheets{$key}) {
           map {
               my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
               if ($name eq $fn) {
           $found=$value;
               }
           } split(/\_\_\_\&\_\_\_/,$oldsheets{$key});
        }
    }
   #
   # Check if still valid
   #
    if ($found) {
        if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
    $found='';
        }
    }
    
    if ($found) {
   #
   # Return what was cached
   #
        @exportarr=split(/\_\_\_\;\_\_\_/,$found);
   
    } else {
   #
   # Not cached
   #        
   
       my $thissheet=&makenewsheet($uname,$udom,$stype,$usymb);
       &readsheet($thissheet,$fn);
       &updatesheet($thissheet);
       &loadrows($thissheet);
       &calcsheet($thissheet); 
       @exportarr=&exportdata($thissheet);
   #
   # Store now
   #
       my $cid=$ENV{'request.course.id'}; 
       my $current='';
       if ($stype eq 'studentcalc') {
          $current=&Apache::lonnet::reply('get:'.
                                        $ENV{'course.'.$cid.'.domain'}.':'.
                                        $ENV{'course.'.$cid.'.num'}.
        ':nohist_calculatedsheets:'.
                                        &Apache::lonnet::escape($key),
                                        $ENV{'course.'.$cid.'.home'});
       } else {
          $current=&Apache::lonnet::reply('get:'.
                                        &getudom($thissheet).':'.
                                        &getuname($thissheet).
        ':nohist_calculatedsheets_'.
                                        $ENV{'request.course.id'}.':'.
                                        &Apache::lonnet::escape($key),
                                        &getuhome($thissheet));
   
       }
       my %currentlystored=();
       unless ($current=~/^error\:/) {
          map {
              my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
              $currentlystored{$name}=$value;
          } split(/\_\_\_\&\_\_\_/,&Apache::lonnet::unescape($current));
       }
       $currentlystored{$fn}=join('___;___',@exportarr);
   
       my $newstore='';
       map {
           if ($newstore) { $newstore.='___&___'; }
           $newstore.=$_.'___=___'.$currentlystored{$_};
       } keys %currentlystored;
       my $now=time;
       if ($stype eq 'studentcalc') {
          &Apache::lonnet::reply('put:'.
                            $ENV{'course.'.$cid.'.domain'}.':'.
                            $ENV{'course.'.$cid.'.num'}.
    ':nohist_calculatedsheets:'.
                            &Apache::lonnet::escape($key).'='.
    &Apache::lonnet::escape($newstore).'&'.
                            &Apache::lonnet::escape($key).'.time='.$now,
                            $ENV{'course.'.$cid.'.home'});
      } else {
          &Apache::lonnet::reply('put:'.
                            &getudom($thissheet).':'.
                            &getuname($thissheet).
    ':nohist_calculatedsheets_'.
                            $ENV{'request.course.id'}.':'.
                            &Apache::lonnet::escape($key).'='.
    &Apache::lonnet::escape($newstore).'&'.
                            &Apache::lonnet::escape($key).'.time='.$now,
                            &getuhome($thissheet));
      }
    }
    return @exportarr;
   }
   # ============================================================ Expiration Dates
   #
   # Load previously cached student spreadsheets for this course
   #
   
   sub expirationdates {
       undef %expiredates;
       my $cid=$ENV{'request.course.id'};
       my $reply=&Apache::lonnet::reply('dump:'.
        $ENV{'course.'.$cid.'.domain'}.':'.
                                        $ENV{'course.'.$cid.'.num'}.
        ':nohist_expirationdates',
                                        $ENV{'course.'.$cid.'.home'});
       unless ($reply=~/^error\:/) {
    map {
               my ($name,$value)=split(/\=/,$_);
               $expiredates{&Apache::lonnet::unescape($name)}
                           =&Apache::lonnet::unescape($value);
           } split(/\&/,$reply);
       }
   }
   
   # ===================================================== Calculated sheets cache
   #
   # Load previously cached student spreadsheets for this course
   #
   
   sub cachedcsheets {
       my $cid=$ENV{'request.course.id'};
       my $reply=&Apache::lonnet::reply('dump:'.
        $ENV{'course.'.$cid.'.domain'}.':'.
                                        $ENV{'course.'.$cid.'.num'}.
        ':nohist_calculatedsheets',
                                        $ENV{'course.'.$cid.'.home'});
       unless ($reply=~/^error\:/) {
    map {
               my ($name,$value)=split(/\=/,$_);
               $oldsheets{&Apache::lonnet::unescape($name)}
                         =&Apache::lonnet::unescape($value);
           } split(/\&/,$reply);
       }
   }
   
   # ===================================================== Calculated sheets cache
   #
   # Load previously cached assessment spreadsheets for this student
   #
   
   sub cachedssheets {
     my ($sname,$sdom,$shome)=@_;
     unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
       my $cid=$ENV{'request.course.id'};
       my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
                ':nohist_calculatedsheets_'.
                                         $ENV{'request.course.id'},
                                        $shome);
       unless ($reply=~/^error\:/) {
    map {
               my ($name,$value)=split(/\=/,$_);
               $oldsheets{&Apache::lonnet::unescape($name)}
                         =&Apache::lonnet::unescape($value);
           } split(/\&/,$reply);
       }
       $loadedcaches{$sname.'_'.$sdom}=1;
     }
   }
   
   # ===================================================== Calculated sheets cache
   #
   # Load previously cached assessment spreadsheets for this student
   #
   
 # ================================================================ Main handler  # ================================================================ Main handler
   #
   # Interactive call to screen
   #
   #
   
   
 sub handler {  sub handler {
     my $r=shift;      my $r=shift;
   
     $uname='';      if ($r->header_only) {
     $udom='';  
     $csec='';  
   
    if ($r->header_only) {  
       $r->content_type('text/html');        $r->content_type('text/html');
       $r->send_http_header;        $r->send_http_header;
       return OK;        return OK;
    }      }
   
   # ---------------------------------------------------- Global directory configs
   
   $includedir=$r->dir_config('lonIncludes');
   $tmpdir=$r->dir_config('lonDaemons').'/tmp/';
   
 # ----------------------------------------------------- Needs to be in a course  # ----------------------------------------------------- Needs to be in a course
   
   if (($ENV{'request.course.fn'}) ||     if ($ENV{'request.course.fn'}) { 
       ($ENV{'request.state'} eq 'construct')) {   
   
 # --------------------------- Get query string for limited number of parameters  # --------------------------- Get query string for limited number of parameters
   
Line 1322  sub handler { Line 1759  sub handler {
     } (split(/&/,$ENV{'QUERY_STRING'}));      } (split(/&/,$ENV{'QUERY_STRING'}));
   
 # ------------------------------------------- Nothing there? Must be login user  # ------------------------------------------- Nothing there? Must be login user
   
       my $aname;
       my $adom;
   
     unless ($ENV{'form.uname'}) {      unless ($ENV{'form.uname'}) {
  $uname=$ENV{'user.name'};   $aname=$ENV{'user.name'};
         $udom=$ENV{'user.domain'};          $adom=$ENV{'user.domain'};
     } else {      } else {
         $uname=$ENV{'form.uname'};          $aname=$ENV{'form.uname'};
         $udom=$ENV{'form.udom'};          $adom=$ENV{'form.udom'};
     }      }
 # ----------------------------------------------------------- Change of target?  
   
     my $reroute=($ENV{'form.utarget'} eq 'export');  
   
 # ------------------------------------------------------------------- Open page  # ------------------------------------------------------------------- Open page
   
Line 1342  sub handler { Line 1780  sub handler {
   
 # --------------------------------------------------------------- Screen output  # --------------------------------------------------------------- Screen output
   
   unless ($reroute) {  
     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');      $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
     $r->print(<<ENDSCRIPT);      $r->print(<<ENDSCRIPT);
 <script language="JavaScript">  <script language="JavaScript">
Line 1367  ENDSCRIPT Line 1804  ENDSCRIPT
        &hiddenfield('usymb',$ENV{'form.usymb'}).         &hiddenfield('usymb',$ENV{'form.usymb'}).
        &hiddenfield('unewfield','').         &hiddenfield('unewfield','').
        &hiddenfield('unewformula',''));         &hiddenfield('unewformula',''));
   }  
   # ---------------------- Make sure that this gets out, even if user hits "stop"
   
     $r->rflush();      $r->rflush();
   
 # ---------------------------------------- Read new sheet or modified worksheet  # ---------------------------------------- Read new sheet or modified worksheet
   
     my $sheetone=initsheet();  
     $r->uri=~/\/(\w+)$/;      $r->uri=~/\/(\w+)$/;
     &settype($sheetone,$1);  
       my $asheet=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
   
   # ------------------------ If a new formula had been entered, go from work copy
   
     if ($ENV{'form.unewfield'}) {      if ($ENV{'form.unewfield'}) {
         $r->print('<h2>Modified Workcopy</h2>');          $r->print('<h2>Modified Workcopy</h2>');
         $ENV{'form.unewformula'}=~s/\'/\"/g;          $ENV{'form.unewformula'}=~s/\'/\"/g;
         $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.          $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
                   $ENV{'form.unewformula'}.'<p>');                    $ENV{'form.unewformula'}.'<p>');
         &setfilename($sheetone,$ENV{'form.ufn'});          &setfilename($asheet,$ENV{'form.ufn'});
  &tmpread($sheetone,$r->dir_config('lonDaemons').'/tmp/',   &tmpread($asheet,
                  $ENV{'form.usymb'},  
                  $ENV{'form.unewfield'},$ENV{'form.unewformula'});                   $ENV{'form.unewfield'},$ENV{'form.unewformula'});
     } elsif ($ENV{'form.saveas'}) {  
         &setfilename($sheetone,$ENV{'form.ufn'});       } elsif ($ENV{'form.saveas'}) {
  &tmpread($sheetone,$r->dir_config('lonDaemons').'/tmp/',          &setfilename($asheet,$ENV{'form.ufn'});
                  $ENV{'form.usymb'});   &tmpread($asheet);
     } else {      } else {
         unless ($ENV{'form.ufn'}) {          &readsheet($asheet,$ENV{'form.ufn'});
     }      }
   
   if (&gettype($sheetone) eq 'classcalc') {  # -------------------------------------------------- Print out user information
 # ---------------------------------- For course view: get courselist and update  
        &updatestudentrows($sheetone);      unless (&gettype($asheet) eq 'classcalc') {
   } else {          $r->print('<p><b>User:</b> '.&getuname($asheet).
 # ----------------- For assessment and student: See if all import rows uptodate                    '<br><b>Domain:</b> '.&getudom($asheet));
           if (&getcsec($asheet) eq '-1') {
              $r->print('<h3><font color=red>'.
                        'Not a student in this course</font></h3>');
           } else {
              $r->print('<br><b>Section/Group:</b> '.&getcsec($asheet));
           }
       }
   
   # ---------------------------------------------------------------- Course title
   
       $r->print('<h1>'.
               $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.'</h1>');
   
   
     if (tie(%parmhash,'GDBM_File',  
        $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER,0640)) {  
        $csec=&Apache::lonnet::usection($udom,$uname,$ENV{'request.course.id'});  
        if ($csec eq '-1') {  
           $r->print('<h3><font color=red>'.  
    "User '$uname' at domain '$udom' not a student in this course</font></h3>");  
        }  
        &updaterows($sheetone);  
        untie(%parmhash);  
    } else {  
        $r->print('<h3><font color=red>'.  
    'Could not initialize import fields (not in a course)</font></h3>');  
    }  
  }  
 # ---------------------------------------------------- See if something to save  # ---------------------------------------------------- See if something to save
   
     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {      if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
         my $fname='';          my $fname='';
  if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {   if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
             $fname=~s/\W/\_/g;              $fname=~s/\W/\_/g;
             if ($fname eq 'default') { $fname='course_default'; }              if ($fname eq 'default') { $fname='course_default'; }
             $fname.='_'.&gettype($sheetone);              $fname.='_'.&gettype($asheet);
             &setfilename($sheetone,$fname);              &setfilename($asheet,$fname);
             $ENV{'form.ufn'}=$fname;              $ENV{'form.ufn'}=$fname;
             my $reply=&writesheet($sheetone);      $r->print('<p>Saving spreadsheet: '.
             unless ($reroute) {                           &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
  $r->print('<p>Saving spreadsheet: '.$reply.'<p>');   }
             }  
             if ($ENV{'form.makedefufn'}) {  
                 my $reply=&Apache::lonnet::reply('put:'.  
                      $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.':'.  
                      $ENV{'course.'.$ENV{'request.course.id'}.'.num'}.  
                      ':environment:spreadsheet_default_'.  
                      &gettype($sheetone).'='.  
                      &Apache::lonnet::escape($fname),  
                      $ENV{'course.'.$ENV{'request.course.id'}.'.home'});  
                unless ($reroute) {  
            $r->print('<p>Making default spreadsheet: '.$reply.'<p>');  
                }  
             }  
         }  
     }      }
   
 # ------------------------------------------------ Write the modified worksheet  # ------------------------------------------------ Write the modified worksheet
   
    &tmpwrite($sheetone,$r->dir_config('lonDaemons').'/tmp/',     $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
               $ENV{'form.usymb'});  
      &tmpwrite($asheet);
   
   # ----------------------------------------------------------------- Save dialog
   
   
 # ----------------------------------------------------- Print user, course, etc  
    unless ($reroute) {  
     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {      if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
         my $fname=$ENV{'form.ufn'};          my $fname=$ENV{'form.ufn'};
         $fname=~s/\_[^\_]+$//;          $fname=~s/\_[^\_]+$//;
Line 1453  ENDSCRIPT Line 1884  ENDSCRIPT
               '<input type=text size=20 name=newfn value="'.$fname.                '<input type=text size=20 name=newfn value="'.$fname.
               '"> (make default: <input type=checkbox name="makedefufn">)<p>');                '"> (make default: <input type=checkbox name="makedefufn">)<p>');
     }      }
     $r->print(&hiddenfield('ufn',$ENV{'form.ufn'}));  
     unless (&gettype($sheetone) eq 'classcalc') {  
         $r->print('<br><b>User:</b> '.$uname.'<br><b>Domain:</b> '.$udom);  
     }  
     $r->print('<h1>'.  
             $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.'</h1>');  
     if ($csec) {  
        $r->print('<h3>Group/Section: '.$csec.'</h3>');  
     }  
    }  
 # -------------------------------------------------------- Import and calculate  
   
     if (&gettype($sheetone) eq 'assesscalc') {      $r->print(&hiddenfield('ufn',&getfilename($asheet)));
  &rowaassess($sheetone,$ENV{'form.usymb'});  
     } elsif  (&gettype($sheetone) eq 'studentcalc') {  # --------------------------------------------------------------- Cached sheets
  &rowazstudent($sheetone);  
     } else {      &expirationdates();
         &rowazclass($sheetone);  
     }      undef %oldsheets;
     my $calcoutput=&calcsheet($sheetone);      undef %loadedcaches;
     unless ($reroute) {  
        $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');      if (&gettype($asheet) eq 'classcalc') {
           $r->print("Loading previously calculated student sheets ...<br>\n");
           $r->rflush();
           &cachedcsheets();
       } elsif (&gettype($asheet) eq 'studentcalc') {
           $r->print("Loading previously calculated assessment sheets ...<br>\n");
           $r->rflush();
           &cachedssheets(&getuname($asheet),&getudom($asheet),
                          &getuhome($asheet));
     }      }
   
 # ------------------------------------------------------- Print or export sheet  # ----------------------------------------------------- Update sheet, load rows
    unless ($reroute) {     
     &outsheet($r,$sheetone);  
   
       $r->print("Loaded sheet(s), updating rows ...<br>\n");
       $r->rflush();
   
       &updatesheet($asheet);
   
       $r->print("Updated rows, loading row data ...<br>\n");
       $r->rflush();
   
       &loadrows($asheet,$r);
   
       $r->print("Loaded row data, calculating sheet ...<br>\n");
       $r->rflush();
   
       my $calcoutput=&calcsheet($asheet);
       $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
   
       &outsheet($r,$asheet);
     $r->print('</form></body></html>');      $r->print('</form></body></html>');
   } else {  
      $r->print(&exportrow($sheetone));  
   }  
 # ------------------------------------------------------------------------ Done  # ------------------------------------------------------------------------ Done
   } else {    } else {
 # ----------------------------- Not in a course, or not allowed to modify parms  # ----------------------------- Not in a course, or not allowed to modify parms
Line 1493  ENDSCRIPT Line 1934  ENDSCRIPT
       return HTTP_NOT_ACCEPTABLE;         return HTTP_NOT_ACCEPTABLE; 
   }    }
     return OK;      return OK;
   
 }  }
   
 1;  1;
 __END__  __END__
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

Removed from v.1.27  
changed lines
  Added in v.1.50


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>