File:  [LON-CAPA] / loncom / interface / lonexttool.pm
Revision 1.7: download - view: text, annotated - select for diffs
Thu Nov 30 14:41:20 2017 UTC (6 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LTI Integration.
  Rename get_domain_ltitools() routine in lonnet.pm as get_domain_lti(),
  and require second argument -- $context -- either: consumer or provider).

# The LearningOnline Network with CAPA
# Launch External Tool Provider (LTI)
#
# $Id: lonexttool.pm,v 1.7 2017/11/30 14:41:20 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/
#

=pod

=head1 NAME

Apache::lonexttool - Tool Provider launcher

=head1 SYNOPSIS


=head1 OVERVIEW

=cut

package Apache::lonexttool;

use strict;
use Apache::Constants qw(:common :http);
use Net::OAuth;
use Encode;
use Digest::SHA;
use UUID::Tiny ':std';
use HTML::Entities;
use Apache::lonlocal;
use Apache::lonnet;
use Apache::loncommon;

sub handler {
    my $r=shift;
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;

    return OK if $r->header_only;

    my $target=$env{'form.grade_target'};
# ------------------------------------------------------------ Print the screen
    if ($target eq 'tex') {
        $r->print(&Apache::lonprintout::print_latex_header($env{'form.latex_type'}));
    }

# Is this even in a course?
    unless ($env{'request.course.id'}) {
        if ($target ne 'tex') {
            &Apache::loncommon::simple_error_page($r,'','Not in a course');
        } else {
            $r->print('\textbf{Not in a course}\end{document}');
        }
        return OK;
    }

    my ($marker,$exttool) = (split(m{/},$r->uri))[4,5];
    $marker=~s/\D//g;

    if (!$marker) {
        if ($target ne 'tex') {
            $r->print(&mt('Invalid Call'));
        } else {
            $r->print('\textbf{'&mt('Invalid Call').'}\end{document}');
        }
        return OK;
    }

    my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $chome = $env{'course.'.$env{'request.course.id'}.'.home'};
    my $is_tool;

    if ($r->uri eq "/adm/$cdom/$cnum/$marker/$exttool") {
        my %toolsettings=&Apache::lonnet::dump('exttool_'.$marker,$cdom,$cnum);
        if ($toolsettings{'id'}) {
            my $idx = $toolsettings{'id'};
            my %ltitools = &Apache::lonnet::get_domain_lti($cdom,'consumer');
            if (ref($ltitools{$idx}) eq 'HASH') {
                my %toolhash = %{$ltitools{$idx}}; 
                $toolhash{'display'} = {
                                           target => $toolsettings{'target'},
                                           width  => $toolsettings{'width'},
                                           height => $toolsettings{'height'},
                                       };
                $toolhash{'crslabel'} = $toolsettings{'crslabel'};
                $toolhash{'crstitle'} = $toolsettings{'crstitle'};
                $toolhash{'crsappend'} = $toolsettings{'crsappend'};
                $is_tool = 1;
                my $launchok = 1;
                if ($target eq 'tex') {
                    $r->print(&mt('External Tool'));
                } else {
                    my $now = time;
                    if ($toolhash{'passback'}) {
                        unless (&set_callback_secret($cdom,$cnum,$marker,'grade',$now,
                                                     \%toolsettings,\%toolhash) eq 'ok') {
                            undef($launchok);
                        }
                    }
                    if ($toolhash{'roster'}) {
                        &set_callback_secret($cdom,$cnum,$marker,'roster',$now,
                                             \%toolsettings,\%toolhash);
                    }
                    my $submittext = &mt('Launch [_1]',$toolhash{'title'});
                    if (($toolhash{'key'} ne '') && ($toolhash{'secret'} ne '') && 
                        ($toolhash{'url'} ne '') && ($launchok)) {
                        my %lti = &lti_params($r,$cnum,$cdom,$idx,$submittext,\%toolhash);
                        my $url = $toolhash{'url'};
                        if ($toolhash{'crsappend'} ne '') {
                            $url .= $toolhash{'crsappend'};
                        }
                        $r->print(&launch_html($url,$toolhash{'key'},$toolhash{'secret'},
                                               $submittext,\%lti));
                    } else {
                        $r->print('<div>'.&mt('External Tool Unavailable').'</div>');
                    }
                }
            }
        }
    }
    unless ($is_tool) {
        if ($target ne 'tex') {
            $r->print('<div>'.&mt('Invalid Call').'</div>');
        } else {
            $r->print('\textbf{'.&mt(Invalid Call).'}\end{document}');
        }
    }
    return OK;
}

sub set_callback_secret {
    my ($cdom,$cnum,$marker,$name,$now,$toolsettings,$toolhash) = @_;
    return unless ((ref($toolsettings) eq 'HASH') && (ref($toolhash) eq 'HASH'));
    my $warning;
    my ($needsnew,$oldsecret,$lifetime);
    if ($name eq 'grade') {  
        $lifetime = $toolhash->{'passbackvalid'}
    } elsif ($name eq 'roster') {
        $lifetime = $toolhash->{'rostervalid'};
    }  
    if ($toolsettings->{$name} eq '') {
        $needsnew = 1;
    } elsif (($toolsettings->{$name.'date'} + $lifetime) < $now) {
        $oldsecret = $toolsettings->{$name.'secret'};
        $needsnew = 1;
    }
    if ($needsnew) {
        if (&get_tool_lock($cdom,$cnum,$marker,$now) eq 'ok') {
            my $secret = UUID::Tiny::create_uuid_as_string(UUID_V4);
            $toolhash->{$name.'secret'} = $secret;
            my %secrethash = (
                           $name.'secret' => $secret,
                           $name.'secretdate' => $now,
                          );
            if ($oldsecret ne '') {
                $secrethash{'old'.$name.'secret'} = $oldsecret;
            }
            my $putres = &Apache::lonnet::put('exttool_'.$marker,
                                              \%secrethash,$cdom,$cnum);
            my $delresult = &release_tool_lock($cdom,$cnum,$marker);
            if ($delresult ne 'ok') {
                $warning = $delresult ;
            }
            if ($putres eq 'ok') {
                return 'ok';
            }
        } else {
            $warning = '<span class="LC_error">'.
                       &mt('Could not obtain exclusive lock').
                       '</span>';
        }
    } else {
        $toolhash->{$name.'secret'} = $toolsettings->{$name.'secret'};
        return 'ok';
    }
    return;
}

sub lti_params {
    my ($r,$cnum,$cdom,$idx,$submittext,$toolsref) = @_;
    my ($version,$context_type,$msgtype,$toolname,$passback,$roster,$locale,
        $crslabel,$crstitle,$gradesecret,$rostersecret,%fields,%rolesmap,
        %display,%custom,@userlangs);
    if (ref($toolsref) eq 'HASH') {
        $version = $toolsref->{'version'};
        $toolname = $toolsref->{'title'};
        $passback = $toolsref->{'passback'};
        $gradesecret = $toolsref->{'gradesecret'};
        $roster = $toolsref->{'roster'};
        $rostersecret = $toolsref->{'rostersecret'};
        $msgtype = $toolsref->{'messagetype'};
        if (ref($toolsref->{'fields'}) eq 'HASH') {
            %fields = %{$toolsref->{'fields'}};
        }
        if (ref($toolsref->{'roles'}) eq 'HASH') {
            %rolesmap = %{$toolsref->{'roles'}};
        }
        if (ref($toolsref->{'display'}) eq 'HASH') {
            %display = %{$toolsref->{'display'}};
        }
        if (ref($toolsref->{'custom'}) eq 'HASH') {
            %custom = %{$toolsref->{'custom'}};
        }
        $crslabel = $toolsref->{'crslabel'};
        $crstitle = $toolsref->{'crstitle'};
    }
    if ($version eq '') {
        $version = 'LTI-1p0';
    }
    if ($context_type eq '') {
        $context_type = 'CourseSection';
    }
    if ($msgtype eq '') {
        $msgtype = 'basic-lti-launch-request';
    }
    if ($crslabel eq '') {
        $crslabel = $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'},
    }
    if ($crstitle eq '') {
        $crstitle = $env{'course.'.$env{'request.course.id'}.'.description'},;
    }
    my $lonhost = $r->dir_config('lonHostID');
    my $loncaparev = $r->dir_config('lonVersion');
    my $uname = $env{'user.name'};
    my $udom = $env{'user.domain'};
    my @possroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
    my ($roleprefix) = ($env{'request.role'} =~ /^(\w+)\./);
    my $ltirole = $rolesmap{$roleprefix};
    unless (grep(/^\Q$ltirole\E$/,@possroles)) {
        $ltirole = 'Learner';
    }
    my $digest_user = &Encode::decode_utf8($uname.':'.$udom);
    $digest_user = &Digest::SHA::sha1_hex($digest_user);
    if ($env{'course.'.$env{'request.course.id'}.'.languages'} ne '') {
        @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                    $env{'course.'.$env{'request.course.id'}.'.languages'}));
    } else {
        my %langhash = &Apache::loncommon::getlangs($uname,$udom);
        if ($langhash{'languages'} ne '') {
            @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
        } else {
            my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
            if ($domdefs{'lang_def'} ne '') {
                @userlangs = ($domdefs{'lang_def'});
            }
        }
    }
    if (scalar(@userlangs) == 1) {
        $locale = $userlangs[0];
    }
    my ($title,$digest_symb);
    my ($symb) = &Apache::lonnet::whichuser();
    if ($symb) {
        $digest_symb = &Encode::decode_utf8($symb);
        $digest_symb = &Digest::SHA::sha1_hex($digest_symb);
        my $navmap = Apache::lonnavmaps::navmap->new();
        if (ref($navmap)) {
            my $res = $navmap->getBySymb($symb);
            if (ref($res)) {
                $title = $res->compTitle();
            }
        }
    }
    my $domdesc = &Apache::lonnet::domain($cdom);
    my $primary_id = &Apache::lonnet::domain($cdom,'primary');
    my $int_dom = &Apache::lonnet::internet_dom($primary_id);
    my $portal_url = &Apache::lonnet::course_portal_url($cnum,$cdom);

    my %ltiparams = (
        lti_version                            => $version,
        lti_message_type                       => $msgtype,
        resource_link_title                    => $title,
        resource_link_id                       => $digest_symb,
        tool_consumer_instance_guid            => $lonhost,
        tool_consumer_instance_description     => $domdesc,
        tool_consumer_info_product_family_code => 'loncapa',
        tool_consumer_instance_name            => $int_dom,  
        tool_consumer_instance_url             => $portal_url,
        tool_consumer_info_version             => $loncaparev,
        user_id                                => $digest_user,
        roles                                  => $ltirole,
        context_id                             => $env{'request.course.id'},
        context_type                           => $context_type,
        context_label                          => $crslabel,
        context_title                          => $crstitle,
        launch_presentation_locale             => $locale,
    );
    my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
    my $crshostname = &Apache::lonnet::hostname($crshome);
    if ($crshostname) {
        my $crsprotocol = $Apache::lonnet::protocol{$crshome};
        unless ($crsprotocol eq 'https') {
            $crsprotocol = 'http';
        }
        if (($passback) || ($roster)) {
            if ($passback) {
                $ltiparams{'lis_outcome_service_url'} = $crsprotocol.'//'.$crshostname.'/adm/service/passback';
                $ltiparams{'ext_ims_lis_basic_outcome_url'} = $ltiparams{'lis_outcome_service_url'};
                if ($gradesecret) {
                    my $result_sig = 
                        Digest::SHA::sha1_hex($gradesecret.':::'.$digest_symb.':::'.$digest_user.':::'.$env{'request.course.id'});
                    $ltiparams{'lis_result_sourcedid'} =
                        $result_sig.':::'.$digest_symb.':::'.$digest_user.':::'.$env{'request.course.id'};
                }
            }
            if ($roster) {
                if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                    $ltiparams{'ext_ims_lis_memberships_url'} = $crsprotocol.'//'.$crshostname.'/adm/service/roster';
                    if ($rostersecret) {
                        my $roster_sig = Digest::SHA::sha1_hex($gradesecret.':::'.$digest_symb.':::'.$env{'request.course.id'});
                        $ltiparams{'ext_ims_lis_memberships_id'} = $roster_sig.':::'.$digest_symb.':::'.$env{'request.course.id'};
                    }
                }
            }
            my %digesthash;
            if ($ltiparams{'lis_result_sourcedid'}) {
                $digesthash{$ltiparams{'lis_result_sourcedid'}} = "$idx\0".time; 
            }
            if ($ltiparams{'ext_ims_lis_memberships_id'}) {
                $digesthash{$ltiparams{'ext_ims_lis_memberships_id'}} = "$idx\0".time; 
            }
            if (($digest_symb) && ($gradesecret || $rostersecret)) {
                $digesthash{$digest_symb} = $symb;
            }
            if (($passback) && ($gradesecret)) {
                $digesthash{$digest_user} = $uname.':'.$udom;
            }
            if (keys(%digesthash)) {
                &Apache::lonnet::put('exttools',\%digesthash,$cdom,$cnum);
            }
        }
    }
    if ($display{'target'}) {
        $ltiparams{'launch_presentation_document_target'} = $display{'target'};
    }
    if ($display{'width'}) {
        $ltiparams{'launch_presentation_width'} = $display{'width'};
    }
    if ($display{'height'}) {
        $ltiparams{'launch_presentation_height'} = $display{'height'};
    }
    if ($fields{'firstname'}) {
        $ltiparams{'lis_person_name_given'} = $env{'environment.firstname'};
    }
    if ($fields{'lastname'}) {
        $ltiparams{'lis_person_name_family'} = $env{'environment.lastname'};
    }
    if ($fields{'fullname'}) {
        $ltiparams{'lis_person_name_full'} = &Apache::loncommon::plainname($uname,$udom);
    }
    if ($fields{'email'}) {
        my %emails = &Apache::loncommon::getemails($uname,$udom);
        my $contact_email;
        foreach my $type ('permanentemail','critnotification','notification') {
            if ($emails{$type} =~ /\@/) {
                $contact_email = $emails{$type};
                last;
            }
        }
        $ltiparams{'lis_person_contact_email_primary'} = $contact_email;
    }
    if ($fields{'user'}) {
        $ltiparams{'lis_person_sourcedid'} = $uname.':'.$udom;
    }
    if (keys(%custom)) {
        foreach my $key (keys(%custom)) {
            my $value = $custom{$key};
            $value =~ s/^\s+|\s+\$//g;
            if ($value =~ /^\QLONCAPA::env{\E([^\}]+)\}$/) {
                if (exists($env{$1})) {
                    $value = $env{$1};
                }
            }
            $ltiparams{'custom_'.$key} = $value;
        }
    }
    foreach my $key (keys(%ltiparams)) {
        $ltiparams{$key} = &Encode::decode_utf8($ltiparams{$key});
    }
    $ltiparams{'basiclti_submit'} = $submittext;
    return %ltiparams;
}

sub launch_html {
    my ($url,$key,$secret,$submittext,$paramsref) = @_;
    my $hashref = &sign_params($url,$key,$secret,$paramsref);
    my $action = &HTML::Entities::encode($url,'<>&"');
    my $form = <<"END";
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<body>
<div id="LCltiLaunch">
<form name="LCltiLaunchForm" id="LCltiLaunchFormId" action="$action" method="post" encType="application/x-www-form-urlencoded">
END
    if (ref($hashref) eq 'HASH') {
        foreach my $item (keys(%{$hashref})) {
            my $type = 'hidden';
            if ($item eq 'basiclti_submit') {
                $type = 'submit';
            }
            $form .= '<input type="'.$type.'" name="'.$item.'" value="'.$hashref->{$item}.'" id="id_'.$item.'" />'."\n";
        }
    }
    $form .= "</form></div>\n";
    $form .= <<"ENDJS";
<script type="text/javascript">
    document.getElementById("LCltiLaunch").style.display = "none";
    nei = document.createElement('input');
    nei.setAttribute('type','hidden');
    nei.setAttribute('name','basiclti_submit');
    nei.setAttribute('value','$submittext');
    document.getElementById("LCltiLaunchFormId").appendChild(nei);
    document.LCltiLaunchForm.submit();
 </script>
ENDJS
    $form .= "</body></html>\n";
    return $form;
}

sub sign_params {
    my ($url,$key,$secret,$paramsref) = @_;
    my $nonce = Digest::SHA::sha1_hex(sprintf("%06x%06x",rand(0xfffff0),rand(0xfffff0)));

    my $request = Net::OAuth->request("request token")->new(
            consumer_key => $key,
            consumer_secret => $secret,
            request_url => $url,
            request_method => 'POST',
            signature_method => 'HMAC-SHA1',
            timestamp => time,
            nonce => $nonce,
            callback => 'about:blank',
            extra_params => $paramsref,
            version      => '1.0',
            );
    $request->sign;
    return $request->to_hash();
}

sub get_tool_lock {
    my ($cdom,$cnum,$marker,$now) = @_;
    # get lock for tool for which gradesecret is being set
    my $lockhash = {
                  $marker."\0".'lock' => $now.':'.$env{'user.name'}.
                                         ':'.$env{'user.domain'},
                   };
    my $tries = 0;
    my $gotlock = &Apache::lonnet::newput('exttools',$lockhash,$cdom,$cnum);

    while (($gotlock ne 'ok') && $tries <3) {
        $tries ++;
        sleep(1);
        $gotlock = &Apache::lonnet::newput('exttools',$lockhash,$cdom,$cnum);
    }
    return $gotlock;
}

sub release_tool_lock {
    my ($cdom,$cnum,$marker) = @_;
    #  remove lock
    my @del_lock = ($marker."\0".'lock');
    my $dellockoutcome=&Apache::lonnet::del('exttools',\@del_lock,$cdom,$cnum);
    if ($dellockoutcome ne 'ok') {
        return ('<div class="LC_error">'
               .&mt('Warning: failed to release lock for exttool: [_1].','<tt>'.$marker.'</tt>')
               .'</div>'
               );
    } else {
        return 'ok';
    }
}

1;

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