--- loncom/interface/lonsource.pm	2004/06/12 01:08:11	1.1
+++ loncom/interface/lonsource.pm	2017/09/29 19:18:10	1.37
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
-# Publication Handler
+# Source Code handler
 #
-# $Id: lonsource.pm,v 1.1 2004/06/12 01:08:11 taceyjo1 Exp $
+# $Id: lonsource.pm,v 1.37 2017/09/29 19:18:10 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -31,69 +31,388 @@
 package Apache::lonsource;
 
 use strict;
-use Apache::lonnet();
+use Apache::lonnet;
 use Apache::loncommon();
 use Apache::lonhtmlcommon();
 use Apache::lonsequence();
 use Apache::Constants qw(:common :http);
 use Apache::lonmeta;
+use Apache::lonenc();
 use Apache::File;
 use Apache::lonlocal;
 use HTML::Entities;
+use LONCAPA qw(:DEFAULT :match);
 
 sub make_link {
-	my ($filename) = @_;
-	my $sourcelink = "http://".$ENV{'SERVER_NAME'}."/adm/source/?filename=".$filename;
-	
-	
-return $sourcelink;
-	
+    my ($filename, $listname) = @_;
+    my $sourcelink = '/adm/source?inhibitmenu=yes&filename='.
+                     &escape(&escape($filename)).'&listname='.
+                     &escape(&escape($listname));
+    return $sourcelink;
 }
 
 sub stage_2 {
-	my ($r, $filename) = @_;
-	$r->print("Comming Soon");
-	return OK;
+    my ($r, $filename, $listname) = @_;
+    my ($author)=($filename=~/\/res\/[^\/]+\/([^\/]+)\//);
+    $r->print(&Apache::loncommon::start_page('Copy Problem Source Code to Authoring Space',undef,
+                                             {'only_body' => 1,})
+             .&mt('Please enter the directory that you would like the source code to go into.')
+             .'<p>'
+             .&mt('Note: the path is in reference to the root of your Authoring Space,'
+                 .' and new directories will be automatically created.')
+             .'</p>');
+    $r->print('<form name="copy" action="/adm/source" target="_parent" method="post">
+              <input type="hidden" name="filename" value="'.$filename.'" />
+              <input type="hidden" name="listname" value="'.$listname.'" />
+              <input type="hidden" name="action" value="copy_stage" />
+              <input type="text" size="50" name="newpath" value="/'.&mt('shared_source').'/'.$author.'" />&nbsp;
+              <input type="submit" value="'.&mt('Copy').'" />
+              </form>'.
+              &Apache::loncommon::end_page());
+    return OK;
+}
+
+sub copy_author {
+    my $role;
+    my $domain;
+    my $author_name;
+    if ($env{'request.role'} =~ m{^ca\.}) {
+        ($role, $domain, $author_name) = split(/\//,$env{'request.role'});
+    } else {
+        $role = "au.";
+        $domain = $env{'user.domain'};
+        $author_name = $env{'user.name'};
+    }
+    return ($role,$author_name,$domain);
+}
+
+
+sub copy_stage {
+    my ($r, $filename, $listname, $newpath) = @_;
+
+    my ($path_to_new_file,$uname,$udom) = &get_path_to_newfile($r,$newpath,$listname);
+
+    #allowed
+    if ($path_to_new_file) {
+        $r->print(&Apache::loncommon::start_page('Copying Source',undef,{'only_body' => 1}));
+        my $result = &Apache::loncfile::exists($uname, $udom, $path_to_new_file);
+        $r->print($result);
+        if (($result) && ($result =~ /published/)) {
+	    &delete_copy_file($r, $newpath, $filename, $path_to_new_file, '1');
+        } elsif (($result) && ($result =~ /exists\!/)) {
+	    &confirm($r, $newpath, $filename, $listname);
+        } else {
+	    &copy_file($r, $newpath, $filename, $path_to_new_file);
+        }
+        $r->print(&Apache::loncommon::end_page());
+    }
+    return;
+}
+
+sub confirm {
+    my ($r, $newpath, $filename, $listname) = @_;
+    $r->print('<b>'.&mt('Press delete to remove file and replace it with a copy of the source you are viewing.').'</b><br /><br />');
+    $r->print('<form name="delete_confirm" action="/adm/source" target="_parent" method="post">
+              <input type="hidden" name="filename" value="'.$filename.'" />
+              <input type="hidden" name="listname" value="'.$listname.'" />
+              <input type="hidden" name="newpath" value="'.$newpath.'" />
+              <input type="hidden" name="action" value="delete_confirm" />
+              <input type="submit" value="Delete" />
+              </form>');
+    return;
+}
+
+sub delete_copy_file {
+    my ($r, $newpath, $filename, $path_to_new_file, $type) = @_;
+    if ($type eq '1') {
+        $r->print('<p><span class="LC_warning">'
+                 .&mt('Cannot delete non-obsolete published file.')
+                 .'</span><br />'
+                 .&mt('Please use the code view in previous window to use shared code.')
+                 .'<br /><br />');
+        $r->print('<form name="delete_done" action="/adm/source" target="_parent" method="post">'
+                 .'<input type="button" value="'.&mt('Close Window').'" name="close"'
+                 .' onclick="window.close()" />'
+                 .'</form></p>');
+        return;
+    } else {
+        $r->print(&Apache::loncommon::start_page('Copying Source',undef,{'only_body' => 1}));
+        if (-e $path_to_new_file) {
+            unless (unlink($path_to_new_file)) {
+                $r->print('<p class="LC_error"">'.&mt('Error:').' '.$!.'</p>');
+                return 0;
+            }
+        } else {
+            $r->print('<p class="LC_error">'.&mt('No such file').'</p>');
+            return 0;
+        }
+        &copy_file($r, $newpath, $filename, $path_to_new_file);
+        $r->print(&Apache::loncommon::end_page());
+        return;
+    }
+}
+
+sub copy_file {
+    my ($r, $newpath, $filename, $path_to_new_file) = @_;
+    $r->print('<b>'.&mt('Creating directories').'</b>');
+
+#Figure out if we are author or co-author
+    my ($role,$author_name,$domain)=&copy_author();
+
+    my $path = $r->dir_config('lonDocRoot')."/priv/$domain/$author_name/";
+    my @directories = split(/\//,$newpath);
+
+    foreach my $now_checking (@directories) {
+        if($now_checking ne '') {
+            $path = $path.'/'.$now_checking;
+            if(-e $path) {} #More moving along, isn't recursion fun'
+
+            else {
+                unless(mkdir($path, 02770)) {
+                    $r->print('<p class="LC_error">'.&mt('Error:').' '.$!.'</p>');
+                    return 0;
+                }
+                unless(chmod(02770, ($path))) {
+                    $r->print('<p class="LC_error"> '.&mt('Error:').' '.$!.'</p>');
+                    return 0;
+                }
+            }
+        } else { } #Just move along
+
+    }
+    $r->print('<br /><b>'.&mt('Copying File').'</b>');
+    my $problem_filename = $Apache::lonnet::perlvar{'lonDocRoot'}.$filename;
+    my $file_output = &includemeta(&Apache::lonnet::getfile($problem_filename),$filename);
+    my $fs=Apache::File->new(">$path_to_new_file");
+    if (defined($fs)) {
+        print $fs $file_output;
+    }
+    $r->print("<br /><br />");
+    $r->print('<form name="copied_file" action="/adm/source" target="_parent" method="post">'
+              .'<input type="button" value="'
+              .&mt('Close Window').'" name="close" onclick="window.close()" />'
+              .'</form>');
+    #Some 1.3'ish feature is to include the derivative feature, will go here..'
+    return;
 }
 
 sub print_item {
-	my ($r, $filename) = @_;
-	$filename = "/home/httpd/html".$filename;
-	my $file_output = &Apache::lonnet::getfile($filename);
-	my ($rows,$cols) = &Apache::edit::textarea_sizes(\$file_output);
-	$r->print('<textarea rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
-	    &HTML::Entities::encode($file_output,'<>&"').'</textarea>');
-	
-	return OK;
-	
+    my ($r,$filename,$listname,$context) = @_;
+    my $file_output;
+    if ($context eq 'view') {
+        $file_output =
+            &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$filename);
+    } else {
+        $file_output =
+            &includemeta(&Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$filename),
+                                                  $filename);
+    }
+    $r->print(&Apache::loncommon::start_page('View Source Code',undef,
+                                             {'only_body' => 1}));
+    if ($file_output ne '') {
+        my $access_to_cstr;
+        my $lonhost = $r->dir_config('lonHostID');
+        if ($context eq 'view') {
+            $r->print('<form name="view" action="" target="_parent" method="post"><span class="LC_info">'.
+                      &mt('Source code is displayed below.').
+                      '</span>'.('&nbsp;' x4).'<input type="button" name="close" onclick="window.close();"'.
+                      ' value="'.&mt('Close Window').'" /></form><hr />');
+        } elsif (&Apache::lonnet::is_library($lonhost)) {
+            my @possdoms = &Apache::lonnet::current_machine_domains();
+            foreach my $dom (@possdoms) {
+                if ($env{"user.role.au./$dom/"}) {
+                    $access_to_cstr = 1;
+                    last;  
+                }
+            }
+            unless ($access_to_cstr) {
+                foreach my $key (keys(%env)) {
+                    if ($key =~ m{^\Quser.role.ca./\E($match_domain)/}) {
+                        my $adom = $1;
+                        if (grep(/^\Q$adom\E$/,@possdoms)) {
+                            $access_to_cstr = 1;
+                            last;
+                        }
+                    }
+                }
+            }
+            if ($access_to_cstr) {
+                $r->print('
+             <form name="copy" action="/adm/source" target="_parent" method="post">
+              <input type="button" value="'.&mt('Close Window').'" name="close" onclick="window.close();" />
+              <input type="hidden" name="filename" value="'.$filename.'" />
+              <input type="hidden" name="listname" value="'.$listname.'" />
+              <input type="hidden" name="action" value="stage2" />
+              <input type="submit" value="'.&mt('Copy to Authoring Space').'" />
+             </form><hr />
+                ');
+            } else {
+                $r->print('<p><span class="LC_info">'.
+                          &mt('Source code is displayed, but you can not copy to Authoring Space, as you do not have an author or co-author role on this server.').
+                          '</span></p><a href="javascript:window.close();">'.&mt('Close Window').
+                          '</a><br /><hr />'
+                         );
+            }
+        } else {
+            $r->print('<p><span class="LC_info">'.
+                      &mt('Source code is displayed, but you can not copy to Authoring Space on this server.').
+                          '</span></p><a href="javascript:window.close();">'.&mt('Close Window').
+                          '</a><br /><hr />'
+                     );
+
+        }
+        my $count=0;
+        my $maxlength=-1;
+        foreach (split ("\n", $file_output)) {
+            $count+=int(length($_)/79);
+            $count++;
+            if (length($_) > $maxlength) {
+                $maxlength = length($_);
+            }
+        }
+        my $rows = $count;
+        my $cols = $maxlength;
+        $r->print('<form name="showsrc" action="" method="post" onsubmit="return false">'."\n".
+                  '<textarea rows="'.$rows.'" cols="'.$cols.'" name="editxmltext">'.
+                  &HTML::Entities::encode($file_output,'<>&"').'</textarea></form>');
+    } else {
+        $r->print('<p class="LC_warning">'.
+                  &mt('Unable to retrieve file contents.').
+                  '</p><a href="javascript:window.close();">'.&mt('Close Window').'</a>'
+                 );
+    }
+    $r->print(&Apache::loncommon::end_page());
+    return;
 }
 
+sub includemeta {
+    my ($file_output,$orgfilename)=@_;
+    my $escfilename=&escape($orgfilename);
+    my $copytime=time;
+    if ($file_output=~/\<meta\s*name\=\"isbasedonres\"/i) {
+	$file_output=~s/(\<meta\s*name\=\"isbasedonres\"\s*content\=\"[^\"]*)\"/$1\,\Q$escfilename\E\"/i;
+    } else {
+	$file_output=~s/(\<(?:html|problem)[^\>]*\>)/$1\n\<meta name=\"isbasedonres\" content=\"\Q$escfilename\E\" \/\>/i;
+    }
+    if ($file_output=~/\<meta\s*name\=\"isbasedontime\"/i) {
+	$file_output=~s/(\<meta\s*name\=\"isbasedontime\"\s*content\=\"[^\"]*)\"/$1\,\Q$copytime\E\"/i;
+    } else {
+	$file_output=~s/(\<(?:html|problem)[^\>]*\>)/$1\n\<meta name=\"isbasedontime\" content=\"\Q$copytime\E\" \/\>/i;
+    }
+    if ($file_output eq '-1') {
+        return;
+    } else {
+        return $file_output;
+    }
+}
 
-sub handler { 
-	my $r=shift;
-	if($ENV{'form.action'} eq 'stage2') { 
-		&stage_2($r, $ENV{'form.filename'});
-	} else {
-	&Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
-	     ['filename']);
-	return FORBIDDEN if !&Apache::lonnet::allowed('cre',$ENV{'form.filename'}) 
-	&Apache::loncommon::content_type($r,'text/html');
-	my $filename = $ENV{'form.filename'};
-	$r->send_http_header;
-	$r->print('		    <form name="copy" action="/adm/source/" target="_parent" method="post">
-				<input type="button" value="Close Window" name="close" onClick="window.close()">
-		      <input type="hidden" name="filename" value="'.$filename.'" />
-		      <input type="hidden" name="action" value="stage2" />
-	              <input type="submit" value="Copy to CSTR" />
-		    </form>');
-	$r->print('<hr />');
-	&print_item($r, $ENV{'form.filename'});
-	}
-	return OK;
+sub get_path_to_newfile {
+    my ($r,$newpath,$listname) = @_;
 
+    #Figure out if we are author or co-author
+    my ($role,$author_name,$domain) = &copy_author();
+
+    # Construct path to copy and filter out any possibly nasty stuff
+    my $path = $r->dir_config('lonDocRoot')."/priv/$domain/$author_name/";
+    my $path_to_new_file = $path."$newpath/$listname";
+    $path_to_new_file=~s/\.\.//g;
+    $path_to_new_file=~s/\~//g;
+    $path_to_new_file=~s/\/+/\//g;
+
+    #Just checking again for access as we want to make sure that it is really ok
+    #now that we have the real path
+
+    my ($uname,$udom)= &Apache::lonnet::constructaccess($path_to_new_file);
+
+    if (!$uname || !$udom) {
+        $r->print(&Apache::loncommon::start_page('Not Allowed',undef,{'only_body' => 1}));
+        $r->print(&mt('Not allowed to create file [_1]', $path_to_new_file));
+        $r->print(&Apache::loncommon::end_page());
+        if (wantarray) {
+            return();
+        } else {
+            return;
+        }
+    }
+    if (wantarray) {
+        return ($path_to_new_file,$uname,$udom);
+    } else {
+        return $path_to_new_file;
+    }
 }
 
+sub handler {
+    my $r=shift;
+    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
+                                            ['filename','listname','viewonly']);
+    my $filename = $env{'form.filename'};
+    my $shownfilename = $filename;
+    $shownfilename =~ s/(`)/'/g;
+    $shownfilename =~ s/\$/\(\$\)/g;
+    my $listname = $env{'form.listname'};
+    my $viewonly = $env{'form.viewonly'};
+
+    if ($viewonly) {
+        my $canview;
+        $filename =~ s/\.\.//g;
+        $filename =~ s/\~//g;
+        $filename =~ s/\/+/\//g;
+        if (($env{'request.course.id'}) && (&Apache::lonnet::is_on_map($filename))) {
+            if ((&Apache::lonnet::metadata(&Apache::lonenc::check_decrypt($filename)) eq 'open') &&
+                (&Apache::lonnet::allowed('cre','/'))) {
+                $canview = 1;
+            } elsif (&Apache::lonnet::allowed('vxc',$env{'request.course.id'})) {
+                my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+                &Apache::lonenc::check_decrypt(\$filename);
+                if (($env{'request.role.domain'} eq $cdom) && ($filename =~ /$LONCAPA::assess_re/)) {
+                    my ($auname) = ($filename =~ m{^\Q/res/$cdom/\E($match_username)/});
+                    if (($env{'request.course.adhocsrcaccess'} ne '') &&
+                        (grep(/^\Q$auname\E$/,split(/,/,$env{'request.course.adhocsrcaccess'})))) {
+                        $canview = 1;
+                    }
+                }
+            }
+        }
+        unless ($canview) {
+            $env{'user.error.msg'}="$shownfilename:cre:1:1:Source code not available";
+            return HTTP_NOT_ACCEPTABLE;
+        }
+    } elsif (&Apache::lonnet::metadata($filename,'sourceavail') ne 'open') {
+        $env{'user.error.msg'}="$shownfilename:cre:1:1:Source code not available";
+        return HTTP_NOT_ACCEPTABLE;
+    }
+    unless (&Apache::lonnet::allowed('bre',$filename)) {
+        $env{'user.error.msg'}="$shownfilename:bre:1:1:Access to resource denied";
+        return HTTP_NOT_ACCEPTABLE;
+    }
+    unless ($viewonly) {
+        unless (&Apache::lonnet::allowed('cre','/')) {
+            $env{'user.error.msg'}="$shownfilename:cre:1:1:Access to source code denied";
+            return HTTP_NOT_ACCEPTABLE;
+        }
+    }
+    my $newpath = $env{'form.newpath'};
+
+    &Apache::loncommon::content_type($r,'text/html');
+    $r->send_http_header;
+
+    if ($viewonly) {
+        &print_item($r,$filename,$listname,'view');
+    } elsif ($env{'form.action'} eq 'stage2') {
+        &stage_2($r,$filename,$listname);
+    } elsif($env{'form.action'} eq 'copy_stage') {
+        &copy_stage($r,$filename,$listname,$newpath);
+    } elsif($env{'form.action'} eq 'delete_confirm') {
+        my $path_to_new_file = &get_path_to_newfile($r,$newpath,$listname);
+        if ($path_to_new_file) {
+            &delete_copy_file($r, $newpath, $filename, $path_to_new_file, '0');
+        }
+    } else {
+        &print_item($r,$filename,$listname);
+    }
+    return OK;
+}
 
 1;
-	
-	
\ No newline at end of file
+
+