File:  [LON-CAPA] / loncom / interface / spreadsheet / lonspreadsheet.pm
Revision 1.67: download - view: text, annotated - select for diffs
Tue Nov 30 15:55:39 2021 UTC (3 years ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6955 IP-based blocking. Pass user'sIP address as third arg to
  loncommon::blockcheck() and second to loncommon::blocking_status().

#
# $Id: lonspreadsheet.pm,v 1.67 2021/11/30 15:55:39 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
# The LearningOnline Network with CAPA
# Spreadsheet/Grades Display Handler
#
# POD required stuff:

=head1 NAME

lonspreadsheet

=head1 SYNOPSIS

Spreadsheet interface to internal LON-CAPA data

=head1 DESCRIPTION

Lonspreadsheet provides course coordinators the ability to manage their
students grades online.  The students are able to view their own grades, but
not the grades of their peers.  The spreadsheet is highly customizable,
offering the ability to use Perl code to manipulate data, as well as many
built-in functions.

=head2 Functions available to user of lonspreadsheet

=over 4

=cut


package Apache::lonspreadsheet;
            
use strict;
use warnings FATAL=>'all';
no warnings 'uninitialized';
use Apache::classcalc();
use Apache::studentcalc();
use Apache::assesscalc();
use Apache::Constants qw(:common :http);
use Apache::lonnet;
use Apache::lonhtmlcommon;
use Apache::lonlocal;
use Apache::loncoursedata();
use Apache::lonquickgrades();
use HTML::Entities();

##
## HTML utility subroutines really should go in lonhtmlcommon
##

sub textfield {
    my ($title,$name,$value)=@_;
    return "\n<p><b>$title:</b><br />".
        '<input type="text" name="'.$name.'" size="80" value="'.$value.'" />';
}

sub hiddenfield {
    my ($name,$value)=@_;
    return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
}

sub selectbox {
    my ($title,$name,$value,%options)=@_;
    my $selout="\n<p><b>$title:</b><br />".'<select name="'.$name.'">';
    foreach (sort keys(%options)) {
        $selout.='<option value="'.$_.'"';
        if ($_ eq $value) { $selout.=' selected="selected"'; }
        $selout.='>'.&mt($options{$_}).'</option>';
    }
    return $selout.'</select>';
}

sub file_dialogs {
    my ($spreadsheet) = @_;
    my $bgcolor = "#FFFFFF";
    my $sheettype = $spreadsheet->{'type'};
    my $result = '';
    my $message = '';
    ##
    ## Deal with saving the spreadsheet
    $spreadsheet->check_formulas_loaded();
    if ((exists($env{'form.save'}) || exists($env{'form.makedefault'})) && 
        exists($env{'form.savefilename'})) {
        $spreadsheet->filename($env{'form.savefilename'});
        my $save_status = $spreadsheet->save();
        if ($save_status ne 'ok') {
            $message .= '<span class="LC_error">'.
                &mt('An error occurred while saving the spreadsheet. The error is: [_1].',
                    $save_status).'</span>';
        } else {
            $message .= '<span class="LC_info">'.&mt('Spreadsheet saved as: [_1] .',
                        '<span class="LC_filename">'.$spreadsheet->filename().'</span>').
                        '</span>';
        }
    } elsif (exists($env{'form.newformula'}) && 
             exists($env{'form.cell'})       && 
             $env{'form.cell'} ne '' ) {
        ##
        ## Make any requested modifications to the spreadsheet
        $spreadsheet->modify_cell($env{'form.cell'},
                                  $env{'form.newformula'});
        $spreadsheet->save_tmp();
        # output that we are dealing with a temporary file
        $result .=&hiddenfield('workcopy',$sheettype);
        if ($env{'form.newformula'} !~ /^\s*$/) {
            $message .='<table><tr>'.
              '<td valign="top"><pre>'.&mt('Cell').' '.$env{'form.cell'}.' = </pre></td>'.
              '<td><pre>'.$env{'form.newformula'}."</pre></td></tr></table>\n";
        } else {
            $message .= &mt('Deleted contents of cell').' '.$env{'form.cell'}.'.';
        }
    }
    ##
    ## Editing code
    $result .=&hiddenfield('cell','').
              &hiddenfield('newformula','');
    ##
    ## Create the save and load dialogs
    my $filename = $spreadsheet->filename();
    my $truefilename = $filename;
    if ($spreadsheet->is_default()) {
        $filename = 'Default';
    }
    my $save_dialog = '<span class="LC_nobreak">'.
        '<input type="submit" name="save" value="'.&mt('Save as').'" /> '.
        '<input type="text" name="savefilename" size="30" value="'.
        $truefilename.'" />'.
        '</span>';
    my $makedefault_dialog = '<input type="submit" name="makedefault" '.
        'value="'.&mt('Save as &amp; Make This Sheet the Default').'"/>';
    #
    my $link = '<a href="javascript:openbrowser'.
        "('sheet','loadfilename','spreadsheet')\">".&mt('Select Spreadsheet File')."</a>";
    my $load=&mt('Load:');
    my $load_dialog = <<END;
<table bgcolor="$bgcolor">
<tr><td><input type="submit" name="load" value="$load" /></td>
    <td><span class="LC_nobreak">
        <input type="text" name="loadfilename" size="20" value="$filename" />
        $link</span>
    </td></tr>
<tr><td>&nbsp;</td><td>
    <select name="fileselect" onchange="document.sheet.loadfilename.value=document.sheet.fileselect.value" >
END
    my $default_filename_set = 0;
    foreach my $sheetfilename ($spreadsheet->othersheets()) {
        $load_dialog .= '    <option value="'.$sheetfilename.'"';
        if ($filename eq $sheetfilename) {
            $load_dialog .= ' selected="selected"';
            $default_filename_set = 1;
        }
        $load_dialog .= '>'.$sheetfilename."</option>\n";
    }
    $load_dialog .= "</select>\n</td><td>&nbsp;</td></tr>\n</table>\n";
        #
    my $headline = &mt('File Dialogs');
    $result .=<<END;
<!-- 
    <fieldset title="File Dialogs" >
    <legend>$headline</legend>
  -->
<!-- load / save dialogs -->
<table cellspacing="2">
<tr>
    <td>$load_dialog</td>
    <td>
        <table bgcolor="$bgcolor">
        <tr><td>$save_dialog</td></tr>
        <tr><td align="center">$makedefault_dialog</td></tr>
        </table>
    </td>
</tr>
</table>
<!--
    </fieldset>
  -->
END
    return ($result,$message);
}

sub handler {
    my $r=shift;
    #
    # HTML Header
    #
    if ($r->header_only) {
        &Apache::loncommon::content_type($r,'text/html');
        $r->send_http_header;
        return OK;
    }
    #
    # Roles Checking
    #
    # Needs to be in a course
    if (! $env{'request.course.fn'}) { 
        # Not in a course, or not allowed to modify parms
        $env{'user.error.msg'}=
            $r->uri.":opa:0:0:Cannot modify spreadsheet";
        return HTTP_NOT_ACCEPTABLE; 
    }
    my ($sheettype) = ($r->uri=~/\/(\w+)$/);
    my $courseid = $env{'request.course.id'};

    ##
    ## Check permissions
    my $allowed_to_edit = &Apache::lonnet::allowed('mgr',
                                                $env{'request.course.id'});
    # Only those instructors/tas/whatevers with complete access
    # (not section restricted) are able to modify spreadsheets.
    my $allowed_to_view =  &Apache::lonnet::allowed('vgr',
                                                $env{'request.course.id'});
    if (! $allowed_to_view) {
        $allowed_to_view = &Apache::lonnet::allowed('vgr',
                    $env{'request.course.id'}.'/'.$env{'request.course.sec'});
        # Those who are restricted by section are allowed to view.
        # The routines in lonstatistics which decide which students'
        # will be shown take care of the restriction by section.
    }

    #
    # Check if display of course gradebook is blocked
    #

    if ($env{'request.course.id'}) {
        my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        my $clientip = &Apache::lonnet::get_requestor_ip($r);
        my ($blocked,$blocktext) =
            &Apache::loncommon::blocking_status('grades',$clientip,$cnum,$cdom);
        if ($blocked) {
            my $checkrole = "cm./$cdom/$cnum";
            if ($env{'request.course.sec'} ne '') {
                $checkrole .= "/$env{'request.course.sec'}";
            }
            unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                    ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                &Apache::lonquickgrades::grades_blocked($r,$blocktext,'spreadsheet');
                return OK;
            }
        }
    }

    #
    # Do not allow users without vgr or mgr priv to continue unless 
    # grading type is set to spreadsheet. 
    #

    if ((!$allowed_to_view) && (!$allowed_to_edit)) {
        if ($env{'course.'.$courseid.'.grading'} eq 'spreadsheet') {
            if ($sheettype ne 'studentcalc') {
                $r->internal_redirect('/adm/studentcalc');
                return OK;
            }
        } else {
            $r->internal_redirect('/adm/quickgrades');
            return OK;
        }
    }
    #
    # Get query string for limited number of parameters
    #
    &Apache::loncommon::get_unprocessed_cgi
        ($ENV{'QUERY_STRING'},['sname','sdomain','usymb','filename','recalc',
                               'output_format','not_first_run']);
    #
    # Deal with restricted student permissions 
    #
    if ($env{'request.role'} =~ /^st\./) {
        delete $env{'form.cell'}       if (exists($env{'form.cell'}));
        delete $env{'form.newformula'} if (exists($env{'form.newformula'}));
    }
    #
    # Determine basic information about the spreadsheet
    #
    my $symb   = undef;
    $symb = $env{'form.usymb'} if (exists($env{'form.usymb'}));
    my $name   = $env{'user.name'};
    my $domain = $env{'user.domain'};
    my $warning;
    if (exists($env{'form.sname'}) && $env{'form.sname'} ne '') {
        if (($env{'form.sname'} ne $env{'user.name'}) ||
            ($env{'form.sdomain'} ne $env{'user.domain'})) {
            if (($allowed_to_view) || ($allowed_to_edit)) {
                if (&Apache::lonnet::homeserver($env{'form.sname'},$env{'form.sdomain'}) ne 'no_host') {
                    $name   = $env{'form.sname'};
                    $domain = $env{'form.sdomain'};
                } else {
                    $warning = &mt('Requested user: "[_1]" does not exist; your own sheet is displayed instead.',$env{'form.sname'}.':'.$env{'form.sdomain'});
                }
            } else {
                $warning = &mt('Your current role is not permitted to display this sheet for the requested user: "[_1]"; your own sheet is displayed instead.',$env{'form.sname'}.':'.$env{'form.sdomain'});
            }
        }
    }
    $env{'form.sname'} = $name;
    $env{'form.sdomain'} = $domain;
    my $section = &Apache::lonnet::getsection($domain,$name,
					      $env{'request.course.id'});
    my @groups;
    if (($env{'user.name'} eq $name) && ($env{'user.domain'} eq $domain)) {
        @groups = &Apache::lonnet::sort_course_groups($env{'request.course.id'},
                                    split(':',$env{'request.course.groups'}));
    } else {
        @groups = &Apache::lonnet::get_users_groups($domain,$name,
                                                    $env{'request.course.id'});
    }

    #
    # Only those able to view others grades will be allowed to continue 
    # if they are not requesting their own.
    if ($sheettype eq 'classcalc') {
        if (!$allowed_to_view) {
            $r->internal_redirect('/adm/studentcalc');
            return OK;
	}
    }
    if ((($name   ne $env{'user.name'} ) ||
         ($domain ne $env{'user.domain'})) && $sheettype ne 'classcalc') {
        # Check that the student is in their section?
        if (exists($env{'request.course.sec'}) && 
            $env{'request.course.sec'} ne '' ) {
            my $stu_sec = &Apache::lonnet::getsection($domain,$name,
						    $env{'request.course.id'});
            if ($stu_sec ne $env{'request.course.sec'}) {
		$env{'user.error.msg'}=
		    $r->uri.":vgr:0:0:Requested student not in your section.";
		return HTTP_NOT_ACCEPTABLE; 
            }
        }
    }

    #
    # Open page, try to prevent browser cache.
    #
    &Apache::loncommon::content_type($r,'text/html');
    &Apache::loncommon::no_cache($r);
    $r->send_http_header;

    #
    # Header....
    #
    my $nothing = &Apache::lonhtmlcommon::javascript_nothing();
    ##
    ## Spit out the javascript required for editing
    ##
    my $js;
    if ($allowed_to_edit) {
	my %lt=&Apache::lonlocal::texthash(
		'ce' => 'Cell',
		'ac' => 'Save',
		'dc' => 'Cancel'
	);
        my $extra_javascript = 
            &Apache::loncommon::browser_and_searcher_javascript();
	
	my $cell_extra_js   = &Apache::loncommon::resize_textarea_js();
	my $cell_edit_start = 
	    &Apache::loncommon::start_page('Cell Edit Window',$cell_extra_js,
					   {'only_body' => 1,
					    'js_ready'  => 1,
					    'add_entries'  => {
						'onresize' => "resize_textarea('LC_newformula','LC_aftertextarea')",
						'onload'   => "resize_textarea('LC_newformula','LC_aftertextarea')",
					    }});
	my $cell_edit_end = 
	    &Apache::loncommon::end_page({'js_ready'  => 1,});

        $js = <<ENDSCRIPT;
<script type="text/javascript">
//<!--
    $extra_javascript

    var editwin;

    function celledit(cellname,cellformula) {
        var edit_text = '';
        // cellformula may contain less-than and greater-than symbols, so
        // we need to escape them?  
        edit_text +='$cell_edit_start';
        edit_text += '<form name="editwinform" action="">';
        edit_text += '<center><h3>$lt{'ce'} '+cellname+'</h3>';
        edit_text += '<textarea id="LC_newformula" name="newformula" ';
        edit_text += ' cols="60" rows="12"; wrap="off" style="width:100%">';
	edit_text += cellformula+'</textarea>';
        edit_text += '<div id="LC_aftertextarea"><br />';
        edit_text += '<input type="button" name="accept" value="$lt{'ac'}"';
        edit_text += ' onclick=\\\'javascript:';
        edit_text += 'opener.document.sheet.cell.value=';
        edit_text +=     '"'+cellname+'";';
        edit_text += 'opener.document.sheet.newformula.value=';
        edit_text +=     'document.editwinform.newformula.value;';
        edit_text += 'opener.document.sheet.submit();';
        edit_text += 'self.close()\\\' />';
        edit_text += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
        edit_text += '<input type="button" name="abort" ';
        edit_text +=     'value="$lt{'dc'}"';
        edit_text += ' onclick="javascript:self.close()" />';
        edit_text += '</center></div></form>$cell_edit_end';

        if (editwin != null && !(editwin.closed) ) {
            editwin.close();
        }

        editwin = window.open($nothing,'CellEditWin','height=280,width=480,scrollbars=no,resizable=yes,alwaysRaised=yes,dependent=yes',true);
        editwin.document.write(edit_text);
        editwin.document.close();
    }
//-->
</script>
ENDSCRIPT
    }
    &Apache::lonhtmlcommon::clear_breadcrumbs();
    &Apache::lonhtmlcommon::add_breadcrumb
        ({href  => $r->uri,
          title => 'Spreadsheet',
          text  => 'Spreadsheet',
          faq   => 134,
          bug   => 'Spreadsheet'});
    $r->print(&Apache::loncommon::start_page('Grades Spreadsheet',$js).
              &Apache::lonhtmlcommon::breadcrumbs('Spreadsheet',
						  'Spreadsheet_About'));

    #
    # Tabs
    # 
    &Apache::lonquickgrades::startGradeScreen($r,'spreadsheet');

    #
    # Open the form
    # 
    if ($warning) {
        $r->print('<p class="LC_info">'.$warning.'</p>');
    }
    $r->print('<form action="'.$r->uri.'" name="sheet" method="post">');
    $r->print(&hiddenfield('sname'  ,$env{'form.sname'}).
              &hiddenfield('sdomain',$env{'form.sdomain'}).
              &hiddenfield('usymb'  ,$env{'form.usymb'}));
    $r->rflush();
    ##
    ## Determine the filename to use
    my $filename = undef;
    if ($allowed_to_edit) {
        $filename = $env{'form.filename'} if (exists($env{'form.filename'}));
        #
        if (exists($env{'form.load'}) && exists($env{'form.loadfilename'})) {
            $filename = $env{'form.loadfilename'};
            $env{'form.workcopy'} = 'no';
        }
    }
    ##
    ## Take care of "backdoor" spreadsheet expiration / recalc stuff
    if ($allowed_to_edit && exists($env{'form.recalc'})) {
        if (exists($env{'form.recalc'})) {
            &Apache::loncoursedata::delete_caches($env{'requres.course.id'});
        }
        if ($env{'form.recalc'} eq 'expireallsheets') {
            &Apache::lonnet::logthis('spreadsheet expired: entire course');
            # expire ALL spreadsheets
            &Apache::lonnet::expirespread('','','studentcalc');
            &Apache::lonnet::expirespread('','','assesscalc');
            $r->print('<h3>'.
                      &mt('Expired spreadsheet caches for all students').
                      '</h3>');
        } elsif ($env{'form.recalc'} =~ /^symb:/) {
            # expire for all students on this symb
            my ($symb) = ($env{'form.recalc'} =~ /^symb:(.*)$/);
            &Apache::lonnet::logthis('spreadsheet expired: symb = '.$symb);
            &Apache::lonnet::expirespread('','','assesscalc',$symb);
            &Apache::lonnet::expirespread('','','studentcalc');
            $r->print('<h3>'.
              &mt('Expired spreadsheet caches for all students for symb  [_1]',
                  $symb).
                      '</h3>');
        } elsif ($env{'form.recalc'} =~ /^student:/) {
            # expire all assessment spreadsheets for this user
            my ($sname,$sdom) = ($env{'form.recalc'}=~/^student:(.*):(.*)$/);
            &Apache::lonnet::logthis('spreadsheet expired: student = '.
                                     $sname.'@'.$sdom);
            if (defined($sname) && defined($sdom)) {
                &Apache::lonnet::expirespread($sname,$sdom,'assesscalc');
                &Apache::lonnet::expirespread($sname,$sdom,'studentcalc');
                $r->print('<h3>'.
                          &mt('Expired spreadsheet caches for student [_1]',
                              $sname.'@'.$sdom).
                          '</h3>');
            }
        }
    }
    ##
    ## Make the spreadsheet
    &Apache::Spreadsheet::initialize_spreadsheet_package();
    my $spreadsheet = undef;
    if ($sheettype eq 'classcalc') {
        $spreadsheet = Apache::classcalc->new($name,$domain,$filename,undef,
					      $section,\@groups);
    } elsif ($sheettype eq 'studentcalc') {
        $spreadsheet = Apache::studentcalc->new($name,$domain,$filename,undef,
						$section,\@groups);
    } elsif ($sheettype eq 'assesscalc' && 
             defined($symb) && 
             $allowed_to_edit) {
        $spreadsheet = Apache::assesscalc->new($name,$domain,$filename,$symb,
					       $section,\@groups);
    } else {
        return HTTP_NOT_ACCEPTABLE;
    }
    if (! defined($spreadsheet)) {
        # error error - run in circles, scream and shout
        return;
    }
    $spreadsheet->initialize();
    #
    # Output selector
    ##
    ## Editing/loading/saving
    if ($allowed_to_edit) {
        my ($html,$action_message) = &file_dialogs($spreadsheet);
        if ($env{'form.makedefault'}) {
            $spreadsheet->make_default();
            if ($action_message) {
                $action_message .= '<br />';
            }
            $action_message .= &mt('Made this spreadsheet the default');
            if ($sheettype eq 'classcalc') {
                $action_message .= ' '.&mt('for the course');
            } elsif ($sheettype eq 'studentcalc') {
                $action_message .= ' '.&mt('for all students');
            } elsif ($sheettype eq 'assesscalc') {
                $action_message .= ' '.&mt('for all assessments');
            }
            $action_message .= '.';
        }
        $r->print('<table><tr><td valign="top">'.
                  $spreadsheet->html_header().
                  '</td>'.
                  '<td valign="center">'.$html."</td></tr></table>\n");
        if ($action_message ne '') {
            $r->print(
                &Apache::loncommon::confirmwrapper(
                    &mt('Last Action:')
                   .$action_message)
            );
        }
        $r->rflush();
    } else {
        $r->print('<table><tr><td>'.$spreadsheet->html_header().
                  "</td></tr></table>\n");
    }
    $r->rflush();
    #
    $r->print("<table><tr>");
    $r->print('<td><input type="submit" value="'.
              &mt('Generate Spreadsheet').'" />'.
              '</td>');
    if ($allowed_to_view) {
        $r->print('<td>'.
                  &Apache::loncommon::help_open_topic("Spreadsheet_About",
                                                      &mt('Spreadsheet Help')).
                  '</td>');
    }
    if ($allowed_to_edit) {
        $r->print('<td>'.
                  &Apache::loncommon::help_open_topic("Spreadsheet_Editing",
                                                      &mt('Editing Help')).
                  '</td>');
    }
    $r->print('</tr></table>');
    #
    # Keep track of the filename
    $r->print(&hiddenfield('filename',$filename));
    #
    # Keep track of the number of times we have been called, sort of.
    $r->print(&hiddenfield('not_first_run','1'));
    #
    if (exists($env{'form.not_first_run'}) || $sheettype ne 'classcalc') {
        $r->print($spreadsheet->get_html_title());
        if ($allowed_to_view || $allowed_to_edit) {
            $r->print($spreadsheet->parent_link());
        }
        $r->rflush();
        $spreadsheet->display($r);
    }
    $r->print('</form>');
    &Apache::lonquickgrades::endGradeScreen($r);
    $r->print(&Apache::loncommon::end_page());
    $spreadsheet->clear_package();
    return OK;
}

1;

__END__


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