'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'
'."\n".
'- '.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'
'."\n".
@@ -9463,29 +11950,63 @@ sub modify_html_form {
}
sub modify_html_refs {
- my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
+ my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
my $container;
if ($context eq 'portfolio') {
$container = $env{'form.container'};
} elsif ($context eq 'coursedoc') {
$container = $env{'form.primaryurl'};
+ } elsif ($context eq 'manage_dependencies') {
+ (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
+ $container = "/$container";
+ } elsif ($context eq 'syllabus') {
+ $container = $url;
} else {
$container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
}
my (%allfiles,%codebase,$output,$content);
my @changes = &get_env_multiple('form.namechange');
- return unless (@changes > 0);
- if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
- return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
+ unless ((@changes > 0) || ($context eq 'syllabus')) {
+ if (wantarray) {
+ return ('',0,0);
+ } else {
+ return;
+ }
+ }
+ if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
+ ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
+ unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
+ if (wantarray) {
+ return ('',0,0);
+ } else {
+ return;
+ }
+ }
$content = &Apache::lonnet::getfile($container);
- return if ($content eq '-1');
+ if ($content eq '-1') {
+ if (wantarray) {
+ return ('',0,0);
+ } else {
+ return;
+ }
+ }
} else {
- return unless ($container =~ /^\Q$dir_root\E/);
+ unless ($container =~ /^\Q$dir_root\E/) {
+ if (wantarray) {
+ return ('',0,0);
+ } else {
+ return;
+ }
+ }
if (open(my $fh,"<$container")) {
$content = join('', <$fh>);
close($fh);
} else {
- return;
+ if (wantarray) {
+ return ('',0,0);
+ } else {
+ return;
+ }
}
}
my ($count,$codebasecount) = (0,0);
@@ -9509,6 +12030,8 @@ sub modify_html_refs {
if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
$count += $numchg;
+ $allfiles{$newname} = $allfiles{$ref};
+ delete($allfiles{$ref});
}
if ($env{'form.embedded_codebase_'.$i} ne '') {
$codebase = &unescape($env{'form.embedded_codebase_'.$i});
@@ -9517,21 +12040,28 @@ sub modify_html_refs {
}
}
}
+ my $skiprewrites;
if ($count || $codebasecount) {
my $saveresult;
- if ($context eq 'portfolio' || $context eq 'coursedoc') {
+ if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
+ ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
if ($url eq $container) {
my ($fname) = ($container =~ m{/([^/]+)$});
$output = ''.&mt('Updated [quant,_1,reference] in [_2].',
$count,''.
- $fname.'').'
';
+ $fname.'').'';
} else {
$output = ''.
&mt('Error: update failed for: [_1].',
''.
$container.'').'
';
}
+ if ($context eq 'syllabus') {
+ unless ($saveresult eq 'ok') {
+ $skiprewrites = 1;
+ }
+ }
} else {
if (open(my $fh,">$container")) {
print $fh $content;
@@ -9547,12 +12077,57 @@ sub modify_html_refs {
}
}
}
+ if (($context eq 'syllabus') && (!$skiprewrites)) {
+ my ($actionurl,$state);
+ $actionurl = "/public/$udom/$uname/syllabus";
+ my ($ignore,$num,$numpathchanges,$existing,$mapping) =
+ &ask_for_embedded_content($actionurl,$state,\%allfiles,
+ \%codebase,
+ {'context' => 'rewrites',
+ 'ignore_remote_references' => 1,});
+ if (ref($mapping) eq 'HASH') {
+ my $rewrites = 0;
+ foreach my $key (keys(%{$mapping})) {
+ next if ($key =~ m{^https?://});
+ my $ref = $mapping->{$key};
+ my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
+ my $attrib;
+ if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
+ $attrib = join('|',@{$allfiles{$mapping->{$key}}});
+ }
+ if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
+ my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
+ $rewrites += $numchg;
+ }
+ }
+ if ($rewrites) {
+ my $saveresult;
+ my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
+ if ($url eq $container) {
+ my ($fname) = ($container =~ m{/([^/]+)$});
+ $output .= ''.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
+ $count,''.
+ $fname.'').'
';
+ } else {
+ $output .= ''.
+ &mt('Error: could not update links in [_1].',
+ ''.
+ $container.'').'
';
+
+ }
+ }
+ }
+ }
} else {
&logthis('Failed to parse '.$container.
' to modify references: '.$parse_result);
}
}
- return $output;
+ if (wantarray) {
+ return ($output,$count,$codebasecount);
+ } else {
+ return $output;
+ }
}
sub check_for_existing {
@@ -9632,11 +12207,11 @@ sub check_for_upload {
if ($currsize < $filesize) {
my $extra = $filesize - $currsize;
if (($current_disk_usage + $extra) > $disk_quota) {
- my $msg = ''.
+ my $msg = ''.
&mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
- ''.$fname.'',$filesize,$currsize).'
'.
- '
'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
- $disk_quota,$current_disk_usage);
+ ''.$fname.'',$filesize,$currsize).''.
+ ''.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
+ $disk_quota,$current_disk_usage).'
';
return ('will_exceed_quota',$msg);
}
}
@@ -9645,21 +12220,21 @@ sub check_for_upload {
}
}
if (($current_disk_usage + $filesize) > $disk_quota){
- my $msg = ''.
- &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.',''.$fname.'',$filesize).''.
- '
'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
+ my $msg = ''.
+ &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.',''.$fname.'',$filesize).'
'.
+ ''.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'
';
return ('will_exceed_quota',$msg);
} elsif ($found_file) {
if ($locked_file) {
- my $msg = '';
+ my $msg = '';
$msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].',''.$fname.'',''.$port_path.$env{'form.currentpath'}.'');
- $msg .= '
';
+ $msg .= '';
$msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.',''.$fname.'');
return ('file_locked',$msg);
} else {
- my $msg = '';
+ my $msg = '';
$msg .= &mt(' A file by that name: [_1] was found in [_2].',''.$fname.'',$port_path.$env{'form.currentpath'});
- $msg .= '
';
+ $msg .= '';
return ('existingfile',$msg);
}
}
@@ -9719,46 +12294,275 @@ sub is_archive_file {
}
sub decompress_form {
- my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements) = @_;
+ my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
my %lt = &Apache::lonlocal::texthash (
this => 'This file is an archive file.',
+ camt => 'This file is a Camtasia archive file.',
+ itsc => 'Its contents are as follows:',
youm => 'You may wish to extract its contents.',
- camt => 'Extraction of contents is recommended for Camtasia zip files.',
- perm => 'Permanently remove archive file after extraction of contents?',
extr => 'Extract contents',
+ auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
+ proa => 'Process automatically?',
yes => 'Yes',
no => 'No',
+ fold => 'Title for folder containing movie',
+ movi => 'Title for page containing embedded movie',
);
- my $output = ''.$lt{'this'}.' '.$lt{'youm'}.'
';
+ my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
+ my ($is_camtasia,$topdir,%toplevel,@paths);
+ my $info = &list_archive_contents($fileloc,\@paths);
+ if (@paths) {
+ foreach my $path (@paths) {
+ $path =~ s{^/}{};
+ if ($path =~ m{^([^/]+)/$}) {
+ $topdir = $1;
+ }
+ if ($path =~ m{^([^/]+)/}) {
+ $toplevel{$1} = $path;
+ } else {
+ $toplevel{$path} = $path;
+ }
+ }
+ }
if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
- $output .= $lt{'camt'};
+ my @camtasia6 = ("$topdir/","$topdir/index.html",
+ "$topdir/media/",
+ "$topdir/media/$topdir.mp4",
+ "$topdir/media/FirstFrame.png",
+ "$topdir/media/player.swf",
+ "$topdir/media/swfobject.js",
+ "$topdir/media/expressInstall.swf");
+ my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
+ "$topdir/$topdir.mp4",
+ "$topdir/$topdir\_config.xml",
+ "$topdir/$topdir\_controller.swf",
+ "$topdir/$topdir\_embed.css",
+ "$topdir/$topdir\_First_Frame.png",
+ "$topdir/$topdir\_player.html",
+ "$topdir/$topdir\_Thumbnails.png",
+ "$topdir/playerProductInstall.swf",
+ "$topdir/scripts/",
+ "$topdir/scripts/config_xml.js",
+ "$topdir/scripts/handlebars.js",
+ "$topdir/scripts/jquery-1.7.1.min.js",
+ "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
+ "$topdir/scripts/modernizr.js",
+ "$topdir/scripts/player-min.js",
+ "$topdir/scripts/swfobject.js",
+ "$topdir/skins/",
+ "$topdir/skins/configuration_express.xml",
+ "$topdir/skins/express_show/",
+ "$topdir/skins/express_show/player-min.css",
+ "$topdir/skins/express_show/spritesheet.png");
+ my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
+ "$topdir/$topdir.mp4",
+ "$topdir/$topdir\_config.xml",
+ "$topdir/$topdir\_controller.swf",
+ "$topdir/$topdir\_embed.css",
+ "$topdir/$topdir\_First_Frame.png",
+ "$topdir/$topdir\_player.html",
+ "$topdir/$topdir\_Thumbnails.png",
+ "$topdir/playerProductInstall.swf",
+ "$topdir/scripts/",
+ "$topdir/scripts/config_xml.js",
+ "$topdir/scripts/techsmith-smart-player.min.js",
+ "$topdir/skins/",
+ "$topdir/skins/configuration_express.xml",
+ "$topdir/skins/express_show/",
+ "$topdir/skins/express_show/spritesheet.min.css",
+ "$topdir/skins/express_show/spritesheet.png",
+ "$topdir/skins/express_show/techsmith-smart-player.min.css");
+ my @diffs = &compare_arrays(\@paths,\@camtasia6);
+ if (@diffs == 0) {
+ $is_camtasia = 6;
+ } else {
+ @diffs = &compare_arrays(\@paths,\@camtasia8_1);
+ if (@diffs == 0) {
+ $is_camtasia = 8;
+ } else {
+ @diffs = &compare_arrays(\@paths,\@camtasia8_4);
+ if (@diffs == 0) {
+ $is_camtasia = 8;
+ }
+ }
+ }
}
- $output .= '
';
- $output .= <<"START";
-
-$lt{'this'} $lt{'youm'}
-
-
END
return $output;
}
+sub decompression_utility {
+ my ($program) = @_;
+ my @utilities = ('tar','gunzip','bunzip2','unzip');
+ my $location;
+ if (grep(/^\Q$program\E$/,@utilities)) {
+ foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
+ '/usr/sbin/') {
+ if (-x $dir.$program) {
+ $location = $dir.$program;
+ last;
+ }
+ }
+ }
+ return $location;
+}
+
+sub list_archive_contents {
+ my ($file,$pathsref) = @_;
+ my (@cmd,$output);
+ my $needsregexp;
+ if ($file =~ /\.zip$/) {
+ @cmd = (&decompression_utility('unzip'),"-l");
+ $needsregexp = 1;
+ } elsif (($file =~ m/\.tar\.gz$/) ||
+ ($file =~ /\.tgz$/)) {
+ @cmd = (&decompression_utility('tar'),"-ztf");
+ } elsif ($file =~ /\.tar\.bz2$/) {
+ @cmd = (&decompression_utility('tar'),"-jtf");
+ } elsif ($file =~ m|\.tar$|) {
+ @cmd = (&decompression_utility('tar'),"-tf");
+ }
+ if (@cmd) {
+ undef($!);
+ undef($@);
+ if (open(my $fh,"-|", @cmd, $file)) {
+ while (my $line = <$fh>) {
+ $output .= $line;
+ chomp($line);
+ my $item;
+ if ($needsregexp) {
+ ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
+ } else {
+ $item = $line;
+ }
+ if ($item ne '') {
+ unless (grep(/^\Q$item\E$/,@{$pathsref})) {
+ push(@{$pathsref},$item);
+ }
+ }
+ }
+ close($fh);
+ }
+ }
+ return $output;
+}
+
sub decompress_uploaded_file {
my ($file,$dir) = @_;
&Apache::lonnet::appenv({'cgi.file' => $file});
@@ -9777,9 +12581,9 @@ sub decompress_uploaded_file {
sub process_decompression {
my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
my ($dir,$error,$warning,$output);
- if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
- $error = &mt('File name not a supported archive file type.').
- '
'.&mt('File name should end with one of: [_1].',
+ if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
+ $error = &mt('Filename not a supported archive file type.').
+ '
'.&mt('Filename should end with one of: [_1].',
'.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
} else {
my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
@@ -9788,8 +12592,6 @@ sub process_decompression {
} else {
my @ids=&Apache::lonnet::current_machine_ids();
my $currdir = "$dir_root/$destination";
- my ($currdirlistref,$currlisterror) =
- &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
if (grep(/^\Q$docuhome\E$/,@ids)) {
$dir = &LONCAPA::propath($docudom,$docuname).
"$dir_root/$destination";
@@ -9800,47 +12602,61 @@ sub process_decompression {
$error = &mt('Archive file not found.');
}
}
- if ($dir eq '') {
+ my (@to_overwrite,@to_skip);
+ if ($env{'form.archive_overwrite_total'} > 0) {
+ my $total = $env{'form.archive_overwrite_total'};
+ for (my $i=0; $i<$total; $i++) {
+ if ($env{'form.archive_overwrite_'.$i} == 1) {
+ push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
+ } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
+ push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
+ }
+ }
+ }
+ my $numskip = scalar(@to_skip);
+ if (($numskip > 0) &&
+ ($numskip == $env{'form.archive_itemcount'})) {
+ $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
+ } elsif ($dir eq '') {
$error = &mt('Directory containing archive file unavailable.');
} elsif (!$error) {
- my ($decompressed,$display) = &decompress_uploaded_file($file,$dir);
+ my ($decompressed,$display);
+ if ($numskip > 0) {
+ my $tempdir = time.'_'.$$.int(rand(10000));
+ mkdir("$dir/$tempdir",0755);
+ system("mv $dir/$file $dir/$tempdir/$file");
+ ($decompressed,$display) =
+ &decompress_uploaded_file($file,"$dir/$tempdir");
+ foreach my $item (@to_skip) {
+ if (($item ne '') && ($item !~ /\.\./)) {
+ if (-f "$dir/$tempdir/$item") {
+ unlink("$dir/$tempdir/$item");
+ } elsif (-d "$dir/$tempdir/$item") {
+ system("rm -rf $dir/$tempdir/$item");
+ }
+ }
+ }
+ system("mv $dir/$tempdir/* $dir");
+ rmdir("$dir/$tempdir");
+ } else {
+ ($decompressed,$display) =
+ &decompress_uploaded_file($file,$dir);
+ }
if ($decompressed eq 'ok') {
- $output = &mt('Files extracted successfully from archive.').'
';
+ $output = ''.
+ &mt('Files extracted successfully from archive.').
+ '
'."\n";
my ($warning,$result,@contents);
my ($newdirlistref,$newlisterror) =
&Apache::lonnet::dirlist($currdir,$docudom,
$docuname,1);
my (%is_dir,%changes,@newitems);
my $dirptr = 16384;
- if (ref($currdirlistref) eq 'ARRAY') {
- my @curritems;
- foreach my $dir_line (@{$currdirlistref}) {
- my ($item,$rest)=split(/\&/,$dir_line,2);
- unless ($item =~ /\.+$/) {
- push(@curritems,$item);
- }
- }
- if (ref($newdirlistref) eq 'ARRAY') {
- foreach my $dir_line (@{$newdirlistref}) {
- my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,4);
- unless ($item =~ /^\.+$/) {
- if ($dirptr&$testdir) {
- $is_dir{$item} = 1;
- }
- push(@newitems,$item);
- }
- }
- my @diffs = &compare_arrays(\@curritems,\@newitems);
- if (@diffs > 0) {
- foreach my $item (@diffs) {
- $changes{$item} = 1;
- }
- }
- }
- } elsif (ref($newdirlistref) eq 'ARRAY') {
+ if (ref($newdirlistref) eq 'ARRAY') {
foreach my $dir_line (@{$newdirlistref}) {
my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
- unless ($item =~ /\.+$/) {
+ unless (($item =~ /^\.+$/) || ($item eq $file) ||
+ ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
push(@newitems,$item);
if ($dirptr&$testdir) {
$is_dir{$item} = 1;
@@ -9857,18 +12673,70 @@ sub process_decompression {
}
}
if (@contents > 0) {
- my (%children,%parent);
- my $wantform = 1;
+ my $wantform;
+ unless ($env{'form.autoextract_camtasia'}) {
+ $wantform = 1;
+ }
+ my (%children,%parent,%dirorder,%titles);
my ($count,$datatable) = &get_extracted($docudom,$docuname,
$currdir,\%is_dir,
\%children,\%parent,
- \@contents,$wantform);
+ \@contents,\%dirorder,
+ \%titles,$wantform);
if ($datatable ne '') {
$output .= &archive_options_form('decompressed',$datatable,
$count,$hiddenelem);
- my $startcount = 3;
+ my $startcount = 6;
$output .= &archive_javascript($startcount,$count,
- %children);
+ \%titles,\%children);
+ }
+ if ($env{'form.autoextract_camtasia'}) {
+ my $version = $env{'form.autoextract_camtasia'};
+ my %displayed;
+ my $total = 1;
+ $env{'form.archive_directory'} = [];
+ foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
+ my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
+ $path =~ s{/$}{};
+ my $item;
+ if ($path ne '') {
+ $item = "$path/$titles{$i}";
+ } else {
+ $item = $titles{$i};
+ }
+ $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
+ if ($item eq $contents[0]) {
+ push(@{$env{'form.archive_directory'}},$i);
+ $env{'form.archive_'.$i} = 'display';
+ $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
+ $displayed{'folder'} = $i;
+ } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
+ (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
+ $env{'form.archive_'.$i} = 'display';
+ $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
+ $displayed{'web'} = $i;
+ } else {
+ if ((($item eq "$contents[0]/media") && ($version == 6)) ||
+ ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
+ ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
+ push(@{$env{'form.archive_directory'}},$i);
+ }
+ $env{'form.archive_'.$i} = 'dependency';
+ }
+ $total ++;
+ }
+ for (my $i=1; $i<$total; $i++) {
+ next if ($i == $displayed{'web'});
+ next if ($i == $displayed{'folder'});
+ $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
+ }
+ $env{'form.phase'} = 'decompress_cleanup';
+ $env{'form.archivedelete'} = 1;
+ $env{'form.archive_count'} = $total-1;
+ $output .=
+ &process_extracted_files('coursedocs',$docudom,
+ $docuname,$destination,
+ $dir_root,$hiddenelem);
}
} else {
$warning = &mt('No new items extracted from archive file.');
@@ -9891,15 +12759,19 @@ sub process_decompression {
}
sub get_extracted {
- my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$wantform) = @_;
+ my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
+ $titles,$wantform) = @_;
my $count = 0;
- my $lastcontainer = 0;
my $depth = 0;
my $datatable;
+ my @hierarchy;
return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
- (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY'));
+ (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
+ (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
foreach my $item (@{$contents}) {
$count ++;
+ @{$dirorder->{$count}} = @hierarchy;
+ $titles->{$count} = $item;
&archive_hierarchy($depth,$count,$parent,$children);
if ($wantform) {
$datatable .= &archive_row($is_dir->{$item},$item,
@@ -9907,25 +12779,26 @@ sub get_extracted {
}
if ($is_dir->{$item}) {
$depth ++;
- $lastcontainer = $count;
- $parent->{$depth} = $lastcontainer;
+ push(@hierarchy,$count);
+ $parent->{$depth} = $count;
$datatable .=
&recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
- \$depth,\$count,\$lastcontainer,
- $children,$parent,$wantform);
+ \$depth,\$count,\@hierarchy,$dirorder,
+ $children,$parent,$titles,$wantform);
$depth --;
- $lastcontainer = $parent->{$depth};
+ pop(@hierarchy);
}
}
return ($count,$datatable);
}
sub recurse_extracted_archive {
- my ($currdir,$docudom,$docuname,$depth,$count,$lastcontainer,
- $children,$parent,$wantform) = @_;
+ my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
+ $children,$parent,$titles,$wantform) = @_;
my $result='';
- unless ((ref($depth)) && (ref($count)) && (ref($lastcontainer)) &&
- (ref($children) eq 'HASH') && (ref($parent) eq 'HASH')) {
+ unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
+ (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
+ (ref($dirorder) eq 'HASH')) {
return $result;
}
my $dirptr = 16384;
@@ -9936,7 +12809,10 @@ sub recurse_extracted_archive {
my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
unless ($item =~ /^\.+$/) {
$$count ++;
+ @{$dirorder->{$$count}} = @{$hierarchy};
+ $titles->{$$count} = $item;
&archive_hierarchy($$depth,$$count,$parent,$children);
+
my $is_dir;
if ($dirptr&$testdir) {
$is_dir = 1;
@@ -9946,15 +12822,15 @@ sub recurse_extracted_archive {
}
if ($is_dir) {
$$depth ++;
- $$lastcontainer = $$count;
- $parent->{$$depth} = $$lastcontainer;
+ push(@{$hierarchy},$$count);
+ $parent->{$$depth} = $$count;
$result .=
&recurse_extracted_archive("$currdir/$item",$docudom,
$docuname,$depth,$count,
- $lastcontainer,$children,
- $parent,$wantform);
+ $hierarchy,$dirorder,$children,
+ $parent,$titles,$wantform);
$$depth --;
- $$lastcontainer = $parent->{$$depth};
+ pop(@{$hierarchy});
}
}
}
@@ -9976,15 +12852,20 @@ sub archive_row {
my ($is_dir,$item,$currdir,$depth,$count) = @_;
my ($name) = ($item =~ m{([^/]+)$});
my %choices = &Apache::lonlocal::texthash (
- 'display' => 'Add as File',
+ 'display' => 'Add as file',
'dependency' => 'Include as dependency',
'discard' => 'Discard',
);
if ($is_dir) {
- $choices{'display'} = &mt('Add as Folder');
+ $choices{'display'} = &mt('Add as folder');
}
- my $output = &start_data_table_row()."\n";
+ my $output = &start_data_table_row().''.$count.' | '."\n";
+ my $offset = 0;
foreach my $action ('display','dependency','discard') {
+ $offset ++;
+ if ($action ne 'display') {
+ $offset ++;
+ }
$output .= ''.
'';
+ if ($action eq 'dependency') {
+ $output .= ' '."\n".
+ &mt('Used by:').' '."\n".
+ ' ';
+ } elsif ($action eq 'display') {
+ $output .= ''."\n".
+ &mt('Title:').' '."\n".
+ ' ';
}
- $output .= ' /> '.$choices{$action}.' | ';
+ $output .= '';
}
$output .= '&').'" />'.(' ' x 2);
@@ -10014,32 +12911,54 @@ sub archive_row {
}
sub archive_options_form {
- my ($form,$output,$count,$hiddenelem) = @_;
- return '';
}
sub archive_javascript {
- my ($startcount,$numitems,%children) = @_;
+ my ($startcount,$numitems,$titles,$children) = @_;
+ return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
+ my $maintitle = $env{'form.comment'};
my $scripttag = <
// 0) {
- var startelement = $startcount + (count-1) * 5;
- for (var j=1; j<4; j++) {
- var item = startelement + j;
- if (form.elements[item].type == 'radio') {
- if (form.elements[item].checked) {
- containerCheck(form,count,j);
- break;
+ var startelement = $startcount + ((count-1) * 7);
+ for (var j=1; j<6; j++) {
+ if ((j != 2) && (j != 4)) {
+ var item = startelement + j;
+ if (form.elements[item].type == 'radio') {
+ if (form.elements[item].checked) {
+ containerCheck(form,count,j);
+ break;
+ }
}
}
}
@@ -10074,35 +12999,139 @@ function propagateCheck(form,count) {
}
numitems = $numitems
-var parents = new Array(numitems)
+var titles = new Array(numitems);
+var parents = new Array(numitems);
for (var i=0; i $b } (keys(%children))) {
- my @contents = split(/:/,$children{$container});
+ foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
+ my @contents = split(/:/,$children->{$container});
for (my $i=0; $i<@contents; $i ++) {
$scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
}
}
+ foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
+ $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
+ }
+
$scripttag .= < 0) {
- var item = $startcount + ((count-1) * 5) + offset;
+ dependencyCheck(form,count,offset);
+ var item = (offset+$startcount)+7*(count-1);
form.elements[item].checked = true;
if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
if (parents[count].length > 0) {
for (var j=0; j 0) {
+ var chosen = (offset+$startcount)+7*(count-1);
+ var depitem = $startcount + ((count-1) * 7) + 4;
+ var currtype = form.elements[depitem].type;
+ if (form.elements[chosen].value == 'dependency') {
+ document.getElementById('arc_depon_'+count).style.display='block';
+ form.elements[depitem].options.length = 0;
+ form.elements[depitem].options[0] = new Option('Select','',true,true);
+ for (var i=1; i<=numitems; i++) {
+ if (i == count) {
+ continue;
+ }
+ var startelement = $startcount + (i-1) * 7;
+ for (var j=1; j<6; j++) {
+ if ((j != 2) && (j!= 4)) {
+ var item = startelement + j;
+ if (form.elements[item].type == 'radio') {
+ if (form.elements[item].checked) {
+ if (form.elements[item].value == 'display') {
+ var n = form.elements[depitem].options.length;
+ form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
+ }
+ }
+ }
+ }
+ }
+ }
+ } else {
+ document.getElementById('arc_depon_'+count).style.display='none';
+ form.elements[depitem].options.length = 0;
+ form.elements[depitem].options[0] = new Option('Select','',true,true);
+ }
+ titleCheck(form,count,offset);
+ }
+}
+
+function propagateSelect(form,count,offset) {
+ if (count > 0) {
+ var item = (1+offset+$startcount)+7*(count-1);
+ var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
+ if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
+ if (parents[count].length > 0) {
+ for (var j=0; j 0) {
+ var item = (offset+$startcount)+7*(count-1);
+ if (form.elements[item].type == 'radio') {
+ if (form.elements[item].value == 'dependency') {
+ if (form.elements[item+1].type == 'select-one') {
+ for (var i=0; i 0) {
+ for (var j=0; j 0) {
+ var chosen = (offset+$startcount)+7*(count-1);
+ var depitem = $startcount + ((count-1) * 7) + 2;
+ var currtype = form.elements[depitem].type;
+ if (form.elements[chosen].value == 'display') {
+ document.getElementById('arc_title_'+count).style.display='block';
+ if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
+ document.getElementById('archive_title_'+count).value=maintitle;
+ }
+ } else {
+ document.getElementById('arc_title_'+count).style.display='none';
+ if (currtype == 'text') {
+ document.getElementById('archive_title_'+count).value='';
+ }
+ }
+ }
+ return;
+}
+
// ]]>
END
@@ -10115,7 +13144,7 @@ sub process_extracted_files {
return unless ($numitems);
my @ids=&Apache::lonnet::current_machine_ids();
my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
- %folders,%containers,%mapinner);
+ %folders,%containers,%mapinner,%prompttofetch);
my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
if (grep(/^\Q$docuhome\E$/,@ids)) {
$prefix = &LONCAPA::propath($docudom,$docuname);
@@ -10132,11 +13161,11 @@ sub process_extracted_files {
if ($env{'form.folderpath'}) {
my @items = split('&',$env{'form.folderpath'});
$folders{'0'} = $items[-2];
- $containers{'0'}='sequence';
- } elsif ($env{'form.pagepath'}) {
- my @items = split('&',$env{'form.pagepath'});
- $folders{'0'} = $items[-2];
- $containers{'0'}='page';
+ if ($env{'form.folderpath'} =~ /\:1$/) {
+ $containers{'0'}='page';
+ } else {
+ $containers{'0'}='sequence';
+ }
}
my @archdirs = &get_env_multiple('form.archive_directory');
if ($numitems) {
@@ -10151,36 +13180,40 @@ sub process_extracted_files {
}
}
}
- my ($output,%children,%parent);
+ my ($output,%children,%parent,%titles,%dirorder,$result);
if (keys(%toplevelitems) > 0) {
my @contents = sort(keys(%toplevelitems));
- my ($count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,
- \%children,\%parent,\@contents);
- }
- my (@above,%hierarchy,%referrer,%orphaned,%todelete);
- foreach my $depth (sort { $a <=> $b } keys(%parent)) {
- push(@above,$parent{$depth});
- foreach my $item (split(/:/,$children{$parent{$depth}})) {
- $hierarchy{$item} = \@above;
- }
+ (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
+ \%parent,\@contents,\%dirorder,\%titles);
}
+ my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
if ($numitems) {
for (my $i=1; $i<=$numitems; $i++) {
+ next if ($env{'form.archive_'.$i} eq 'dependency');
my $path = $env{'form.archive_content_'.$i};
if ($path =~ /^\Q$pathtocheck\E/) {
if ($env{'form.archive_'.$i} eq 'discard') {
if ($prefix ne '' && $path ne '') {
if (-e $prefix.$path) {
- $todelete{$prefix.$path} = 1;
+ if ((@archdirs > 0) &&
+ (grep(/^\Q$i\E$/,@archdirs))) {
+ $todeletedir{$prefix.$path} = 1;
+ } else {
+ $todelete{$prefix.$path} = 1;
+ }
}
}
} elsif ($env{'form.archive_'.$i} eq 'display') {
- my ($title,$url,$outer);
+ my ($docstitle,$title,$url,$outer);
($title) = ($path =~ m{/([^/]+)$});
+ $docstitle = $env{'form.archive_title_'.$i};
+ if ($docstitle eq '') {
+ $docstitle = $title;
+ }
$outer = 0;
- if (ref($hierarchy{$i}) eq 'ARRAY') {
- if (@{$hierarchy{$i}} > 0) {
- foreach my $item (reverse(@{$hierarchy{$i}})) {
+ if (ref($dirorder{$i}) eq 'ARRAY') {
+ if (@{$dirorder{$i}} > 0) {
+ foreach my $item (reverse(@{$dirorder{$i}})) {
if ($env{'form.archive_'.$item} eq 'display') {
$outer = $item;
last;
@@ -10195,19 +13228,23 @@ sub process_extracted_files {
next if ($fatal);
if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
if ($context eq 'coursedocs') {
- $mapinner{$i} = time;
+ $mapinner{$i} = time;
$folders{$i} = 'default_'.$mapinner{$i};
$containers{$i} = 'sequence';
my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
$folders{$i}.'.'.$containers{$i};
my $newidx = &LONCAPA::map::getresidx();
$LONCAPA::map::resources[$newidx]=
- $title.':'.$url.':false:normal:res';
+ $docstitle.':'.$url.':false:normal:res';
push(@LONCAPA::map::order,$newidx);
my ($outtext,$errtext) =
&LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
$docuname.'/'.$folders{$outer}.
- '.'.$containers{$outer},1);
+ '.'.$containers{$outer},1,1);
+ $newseqid{$i} = $newidx;
+ unless ($errtext) {
+ $result .= '- '.&mt('Folder: [_1] added to course',$docstitle).'
'."\n";
+ }
}
} else {
if ($context eq 'coursedocs') {
@@ -10223,31 +13260,111 @@ sub process_extracted_files {
}
if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
+ $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
+ unless ($ishome) {
+ my $fetch = "$newdest{$i}/$title";
+ $fetch =~ s/^\Q$prefix$dir\E//;
+ $prompttofetch{$fetch} = 1;
+ }
}
$LONCAPA::map::resources[$newidx]=
- $title.':'.$url.':false:normal:res';
+ $docstitle.':'.$url.':false:normal:res';
push(@LONCAPA::map::order, $newidx);
my ($outtext,$errtext)=
&LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
$docuname.'/'.$folders{$outer}.
- '.'.$containers{$outer},1);
+ '.'.$containers{$outer},1,1);
+ unless ($errtext) {
+ if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
+ $result .= '- '.&mt('File: [_1] added to course',$docstitle).'
'."\n";
+ }
+ }
}
}
- } elsif ($env{'form.archive_'.$i} eq 'dependency') {
- if (ref($hierarchy{$i}) eq 'ARRAY') {
- foreach my $item (reverse(@{$hierarchy{$i}})) {
- if ($env{'form.archive_'.$item} eq 'display') {
- $referrer{$i} = $item;
- last;
- #FIXME identify as dependency in db file
- #FIXME need to move item to referrer location
- #FIXME need to setup httprefs so access allowed
- } elsif ($env{'form.archive_'.$item} eq 'discard') {
- $orphaned{$i} = $item;
- last;
+ }
+ } else {
+ $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).' ';
+ }
+ }
+ for (my $i=1; $i<=$numitems; $i++) {
+ next unless ($env{'form.archive_'.$i} eq 'dependency');
+ my $path = $env{'form.archive_content_'.$i};
+ if ($path =~ /^\Q$pathtocheck\E/) {
+ my ($title) = ($path =~ m{/([^/]+)$});
+ $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
+ if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
+ if (ref($dirorder{$i}) eq 'ARRAY') {
+ my ($itemidx,$fullpath,$relpath);
+ if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
+ my $container = $dirorder{$referrer{$i}}->[-1];
+ for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
+ if ($dirorder{$i}->[$j] eq $container) {
+ $itemidx = $j;
+ }
+ }
+ }
+ if ($itemidx eq '') {
+ $itemidx = 0;
+ }
+ if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
+ if ($mapinner{$referrer{$i}}) {
+ $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
+ for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
+ if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
+ unless (defined($newseqid{$dirorder{$i}->[$j]})) {
+ $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
+ $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
+ if (!-e $fullpath) {
+ mkdir($fullpath,0755);
+ }
+ }
+ } else {
+ last;
+ }
+ }
+ }
+ } elsif ($newdest{$referrer{$i}}) {
+ $fullpath = $newdest{$referrer{$i}};
+ for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
+ if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
+ $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
+ last;
+ } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
+ unless (defined($newseqid{$dirorder{$i}->[$j]})) {
+ $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
+ $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
+ if (!-e $fullpath) {
+ mkdir($fullpath,0755);
+ }
+ }
+ } else {
+ last;
+ }
+ }
+ }
+ if ($fullpath ne '') {
+ if (-e "$prefix$path") {
+ system("mv $prefix$path $fullpath/$title");
+ }
+ if (-e "$fullpath/$title") {
+ my $showpath;
+ if ($relpath ne '') {
+ $showpath = "$relpath/$title";
+ } else {
+ $showpath = "/$title";
+ }
+ $result .= '- '.&mt('[_1] included as a dependency',$showpath).'
'."\n";
+ }
+ unless ($ishome) {
+ my $fetch = "$fullpath/$title";
+ $fetch =~ s/^\Q$prefix$dir\E//;
+ $prompttofetch{$fetch} = 1;
}
}
}
+ } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
+ $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
+ $path,$env{'form.archive_content_'.$referrer{$i}}).' ';
}
} else {
$warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).' ';
@@ -10256,9 +13373,36 @@ sub process_extracted_files {
if (keys(%todelete)) {
foreach my $key (keys(%todelete)) {
unlink($key);
- unless ($ishome) {
- #FIXME Need to notify homeserver to delete files.
- }
+ }
+ }
+ if (keys(%todeletedir)) {
+ foreach my $key (keys(%todeletedir)) {
+ rmdir($key);
+ }
+ }
+ foreach my $dir (sort(keys(%is_dir))) {
+ if (($pathtocheck ne '') && ($dir ne '')) {
+ &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
+ }
+ }
+ if ($result ne '') {
+ $output .= ''."\n".
+ $result."\n".
+ ' ';
+ }
+ unless ($ishome) {
+ my $replicationfail;
+ foreach my $item (keys(%prompttofetch)) {
+ my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
+ unless ($fetchresult eq 'ok') {
+ $replicationfail .= '- '.$item.'
'."\n";
+ }
+ }
+ if ($replicationfail) {
+ $output .= ''.
+ &mt('Course home server failed to retrieve:').' '.
+ $replicationfail.
+ ' ';
}
}
} else {
@@ -10274,6 +13418,90 @@ sub process_extracted_files {
return $output;
}
+sub cleanup_empty_dirs {
+ my ($path) = @_;
+ if (($path ne '') && (-d $path)) {
+ if (opendir(my $dirh,$path)) {
+ my @dircontents = grep(!/^\./,readdir($dirh));
+ my $numitems = 0;
+ foreach my $item (@dircontents) {
+ if (-d "$path/$item") {
+ &cleanup_empty_dirs("$path/$item");
+ if (-e "$path/$item") {
+ $numitems ++;
+ }
+ } else {
+ $numitems ++;
+ }
+ }
+ if ($numitems == 0) {
+ rmdir($path);
+ }
+ closedir($dirh);
+ }
+ }
+ return;
+}
+
+=pod
+
+=item * &get_folder_hierarchy()
+
+Provides hierarchy of names of folders/sub-folders containing the current
+item,
+
+Inputs: 3
+ - $navmap - navmaps object
+
+ - $map - url for map (either the trigger itself, or map containing
+ the resource, which is the trigger).
+
+ - $showitem - 1 => show title for map itself; 0 => do not show.
+
+Outputs: 1 @pathitems - array of folder/subfolder names.
+
+=cut
+
+sub get_folder_hierarchy {
+ my ($navmap,$map,$showitem) = @_;
+ my @pathitems;
+ if (ref($navmap)) {
+ my $mapres = $navmap->getResourceByUrl($map);
+ if (ref($mapres)) {
+ my $pcslist = $mapres->map_hierarchy();
+ if ($pcslist ne '') {
+ my @pcs = split(/,/,$pcslist);
+ foreach my $pc (@pcs) {
+ if ($pc == 1) {
+ push(@pathitems,&mt('Main Content'));
+ } else {
+ my $res = $navmap->getByMapPc($pc);
+ if (ref($res)) {
+ my $title = $res->compTitle();
+ $title =~ s/\W+/_/g;
+ if ($title ne '') {
+ push(@pathitems,$title);
+ }
+ }
+ }
+ }
+ }
+ if ($showitem) {
+ if ($mapres->{ID} eq '0.0') {
+ push(@pathitems,&mt('Main Content'));
+ } else {
+ my $maptitle = $mapres->compTitle();
+ $maptitle =~ s/\W+/_/g;
+ if ($maptitle ne '') {
+ push(@pathitems,$maptitle);
+ }
+ }
+ }
+ }
+ }
+ return @pathitems;
+}
+
=pod
=item * &get_turnedin_filepath()
@@ -10327,6 +13555,9 @@ sub get_turnedin_filepath {
my $title = $res->compTitle();
$title =~ s/\W+/_/g;
if ($title ne '') {
+ if (($pc > 1) && (length($title) > 12)) {
+ $title = substr($title,0,12);
+ }
push(@pathitems,$title);
}
}
@@ -10335,6 +13566,9 @@ sub get_turnedin_filepath {
my $maptitle = $mapres->compTitle();
$maptitle =~ s/\W+/_/g;
if ($maptitle ne '') {
+ if (length($maptitle) > 12) {
+ $maptitle = substr($maptitle,0,12);
+ }
push(@pathitems,$maptitle);
}
unless ($env{'request.state'} eq 'construct') {
@@ -10375,6 +13609,9 @@ sub get_turnedin_filepath {
$restitle = time;
}
}
+ if (length($restitle) > 12) {
+ $restitle = substr($restitle,0,12);
+ }
push(@pathitems,$restitle);
$path .= join('/',@pathitems);
}
@@ -10881,7 +14118,7 @@ sub DrawBarGraph {
@Labels = @$labels;
} else {
for (my $i=0;$i<@{$Values[0]};$i++) {
- push (@Labels,$i+1);
+ push(@Labels,$i+1);
}
}
#
@@ -11312,16 +14549,20 @@ sub restore_settings {
=item * &build_recipient_list()
-Build recipient lists for five types of e-mail:
+Build recipient lists for following types of e-mail:
(a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
-(d) Help requests, (e) Course requests needing approval, generated by
-lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
-loncoursequeueadmin.pm respectively.
+(d) Help requests, (e) Course requests needing approval, (f) loncapa
+module change checking, student/employee ID conflict checks, as
+generated by lonerrorhandler.pm, CHECKRPMS, loncron,
+lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
Inputs:
defmail (scalar - email address of default recipient),
-mailing type (scalar - errormail, packagesmail, or helpdeskmail),
+mailing type (scalar: errormail, packagesmail, helpdeskmail,
+requestsmail, updatesmail, or idconflictsmail).
+
defdom (domain for which to retrieve configuration settings),
+
origmail (scalar - email address of recipient from loncapa.conf,
i.e., predates configuration by DC via domainprefs.pm
@@ -11336,9 +14577,9 @@ Returns: comma separated list of address
sub build_recipient_list {
my ($defmail,$mailing,$defdom,$origmail) = @_;
my @recipients;
- my $otheremails;
+ my ($otheremails,$lastresort,$allbcc,$addtext);
my %domconfig =
- &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
+ &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
if (ref($domconfig{'contacts'}) eq 'HASH') {
if (exists($domconfig{'contacts'}{$mailing})) {
if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
@@ -11350,14 +14591,96 @@ sub build_recipient_list {
push(@recipients,$addr);
}
}
- $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
+ }
+ $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
+ if ($mailing eq 'helpdeskmail') {
+ if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
+ my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
+ my @ok_bccs;
+ foreach my $bcc (@bccs) {
+ $bcc =~ s/^\s+//g;
+ $bcc =~ s/\s+$//g;
+ if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
+ if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
+ push(@ok_bccs,$bcc);
+ }
+ }
+ }
+ if (@ok_bccs > 0) {
+ $allbcc = join(', ',@ok_bccs);
+ }
+ }
+ $addtext = $domconfig{'contacts'}{$mailing}{'include'};
}
}
} elsif ($origmail ne '') {
- push(@recipients,$origmail);
+ $lastresort = $origmail;
}
} elsif ($origmail ne '') {
- push(@recipients,$origmail);
+ $lastresort = $origmail;
+ }
+
+ if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
+ unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
+ my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
+ my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
+ my %what = (
+ perlvar => 1,
+ );
+ my $primary = &Apache::lonnet::domain($defdom,'primary');
+ if ($primary) {
+ my $gotaddr;
+ my ($result,$returnhash) =
+ &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
+ if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
+ if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
+ $lastresort = $returnhash->{'lonSupportEMail'};
+ $gotaddr = 1;
+ }
+ }
+ unless ($gotaddr) {
+ my $uintdom = &Apache::lonnet::internet_dom($primary);
+ my $intdom = &Apache::lonnet::internet_dom($lonhost);
+ unless ($uintdom eq $intdom) {
+ my %domconfig =
+ &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
+ if (ref($domconfig{'contacts'}) eq 'HASH') {
+ if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
+ my @contacts = ('adminemail','supportemail');
+ foreach my $item (@contacts) {
+ if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
+ my $addr = $domconfig{'contacts'}{$item};
+ if (!grep(/^\Q$addr\E$/,@recipients)) {
+ push(@recipients,$addr);
+ }
+ }
+ }
+ if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
+ $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
+ }
+ if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
+ my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
+ my @ok_bccs;
+ foreach my $bcc (@bccs) {
+ $bcc =~ s/^\s+//g;
+ $bcc =~ s/\s+$//g;
+ if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
+ if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
+ push(@ok_bccs,$bcc);
+ }
+ }
+ }
+ if (@ok_bccs > 0) {
+ $allbcc = join(', ',@ok_bccs);
+ }
+ }
+ $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
+ }
+ }
+ }
+ }
+ }
+ }
}
if (defined($defmail)) {
if ($defmail ne '') {
@@ -11377,8 +14700,102 @@ sub build_recipient_list {
}
}
}
- my $recipientlist = join(',',@recipients);
- return $recipientlist;
+ if ($mailing eq 'helpdesk') {
+ if ((!@recipients) && ($lastresort ne '')) {
+ push(@recipients,$lastresort);
+ }
+ } elsif ($lastresort ne '') {
+ if (!grep(/^\Q$lastresort\E$/,@recipients)) {
+ push(@recipients,$lastresort);
+ }
+ }
+ my $recipientlist = join(',',@recipients);
+ if (wantarray) {
+ return ($recipientlist,$allbcc,$addtext);
+ } else {
+ return $recipientlist;
+ }
+}
+
+############################################################
+############################################################
+
+=pod
+
+=over 4
+
+=item * &mime_email()
+
+Sends an email with a possible attachment
+
+Inputs:
+
+=over 4
+
+from - Sender's email address
+
+to - Email address of recipient
+
+subject - Subject of email
+
+body - Body of email
+
+cc_string - Carbon copy email address
+
+bcc - Blind carbon copy email address
+
+type - File type of attachment
+
+attachment_path - Path of file to be attached
+
+file_name - Name of file to be attached
+
+attachment_text - The body of an attachment of type "TEXT"
+
+=back
+
+=back
+
+=cut
+
+############################################################
+############################################################
+
+sub mime_email {
+ my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path,
+ $file_name, $attachment_text) = @_;
+ my $msg = MIME::Lite->new(
+ From => $from,
+ To => $to,
+ Subject => $subject,
+ Type =>'TEXT',
+ Data => $body,
+ );
+ if ($cc_string ne '') {
+ $msg->add("Cc" => $cc_string);
+ }
+ if ($bcc ne '') {
+ $msg->add("Bcc" => $bcc);
+ }
+ $msg->attr("content-type" => "text/plain");
+ $msg->attr("content-type.charset" => "UTF-8");
+ # Attach file if given
+ if ($attachment_path) {
+ unless ($file_name) {
+ if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
+ }
+ my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
+ $msg->attach(Type => $type,
+ Path => $attachment_path,
+ Filename => $file_name
+ );
+ # Otherwise attach text if given
+ } elsif ($attachment_text) {
+ $msg->attach(Type => 'TEXT',
+ Data => $attachment_text);
+ }
+ # Send it
+ $msg->send('sendmail');
}
############################################################
@@ -11488,6 +14905,8 @@ sub extract_categories {
$trailstr = &mt('Official courses (with institutional codes)');
} elsif ($name eq 'communities') {
$trailstr = &mt('Communities');
+ } elsif ($name eq 'placement') {
+ $trailstr = &mt('Placement Tests');
} else {
$trailstr = $name;
}
@@ -11517,7 +14936,7 @@ sub extract_categories {
=pod
-=item *&recurse_categories()
+=item * &recurse_categories()
Recursively used to generate breadcrumb trails for course categories.
@@ -11588,7 +15007,7 @@ sub recurse_categories {
=pod
-=item *&assign_categories_table()
+=item * &assign_categories_table()
Create a datatable for display of hierarchical categories in a domain,
with checkboxes to allow a course to be categorized.
@@ -11602,12 +15021,15 @@ currcat - scalar with an & separated lis
type - scalar contains course type (Course or Community).
+disabled - scalar (optional) contains disabled="disabled" if input elements are
+ to be readonly (e.g., Domain Helpdesk role viewing course settings).
+
Returns: $output (markup to be displayed)
=cut
sub assign_categories_table {
- my ($cathash,$currcat,$type) = @_;
+ my ($cathash,$currcat,$type,$disabled) = @_;
my $output;
if (ref($cathash) eq 'HASH') {
my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
@@ -11626,8 +15048,10 @@ sub assign_categories_table {
next if ($parent eq 'instcode');
if ($type eq 'Community') {
next unless ($parent eq 'communities');
+ } elsif ($type eq 'Placement') {
+ next unless ($parent eq 'placement');
} else {
- next if ($parent eq 'communities');
+ next if (($parent eq 'communities') || ($parent eq 'placement'));
}
my $css_class = $itemcount%2?' class="LC_odd_row"':'';
my $item = &escape($parent).'::0';
@@ -11640,14 +15064,16 @@ sub assign_categories_table {
my $parent_title = $parent;
if ($parent eq 'communities') {
$parent_title = &mt('Communities');
+ } elsif ($parent eq 'placement') {
+ $parent_title = &mt('Placement Tests');
}
$table .= ''.
''.$parent_title.''.
+ $item.'"'.$checked.$disabled.' />'.$parent_title.''.
' | ';
my $depth = 1;
push(@path,$parent);
- $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
+ $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
pop(@path);
$table .= ' | ';
$itemcount ++;
@@ -11665,7 +15091,7 @@ sub assign_categories_table {
=pod
-=item *&assign_category_rows()
+=item * &assign_category_rows()
Create a datatable row for display of nested categories in a domain,
with checkboxes to allow a course to be categorized,called recursively.
@@ -11686,12 +15112,15 @@ path - Array containing all categories b
currcategories - reference to array of current categories assigned to the course
+disabled - scalar (optional) contains disabled="disabled" if input elements are
+ to be readonly (e.g., Domain Helpdesk role viewing course settings).
+
Returns: $output (markup to be displayed).
=cut
sub assign_category_rows {
- my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
+ my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
my ($text,$name,$item,$chgstr);
if (ref($cats) eq 'ARRAY') {
my $maxdepth = scalar(@{$cats});
@@ -11699,7 +15128,7 @@ sub assign_category_rows {
if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
my $numchildren = @{$cats->[$depth]{$parent}};
my $css_class = $itemcount%2?' class="LC_odd_row"':'';
- $text .= '';
+ $text .= '';
for (my $j=0; $j<$numchildren; $j++) {
$name = $cats->[$depth]{$parent}[$j];
$item = &escape($name).':'.&escape($parent).':'.$depth;
@@ -11714,12 +15143,12 @@ sub assign_category_rows {
}
$text .= ''.
+ $item.'"'.$checked.$disabled.' />'.$name.''.
''.
' | ';
if (ref($path) eq 'ARRAY') {
push(@{$path},$name);
- $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
+ $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
pop(@{$path});
}
$text .= ' | ';
@@ -11731,6 +15160,12 @@ sub assign_category_rows {
return $text;
}
+=pod
+
+=back
+
+=cut
+
############################################################
############################################################
@@ -11747,7 +15182,7 @@ sub commit_customrole {
}
sub commit_standardrole {
- my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
+ my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
my ($output,$logmsg,$linefeed);
if ($context eq 'auto') {
$linefeed = "\n";
@@ -11756,7 +15191,7 @@ sub commit_standardrole {
}
if ($three eq 'st') {
my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
- $one,$two,$sec,$context);
+ $one,$two,$sec,$context,$credits);
if (($result =~ /^error/) || ($result eq 'not_in_class') ||
($result eq 'unknown_course') || ($result eq 'refused')) {
$output = $logmsg.' '.&mt('Error: ').$result."\n";
@@ -11787,7 +15222,8 @@ sub commit_standardrole {
}
sub commit_studentrole {
- my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
+ my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
+ $credits) = @_;
my ($result,$linefeed,$oldsecurl,$newsecurl);
if ($context eq 'auto') {
$linefeed = "\n";
@@ -11834,7 +15270,11 @@ sub commit_studentrole {
}
}
if (($expire_role_result eq 'ok') || ($secchange == 0)) {
- $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
+ $modify_section_result =
+ &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
+ undef,undef,undef,$sec,
+ $end,$start,'','',$cid,
+ '',$context,$credits);
if ($modify_section_result =~ /^ok/) {
if ($secchange == 1) {
if ($sec eq '') {
@@ -11856,7 +15296,7 @@ sub commit_studentrole {
}
}
} else {
- if ($secchange) {
+ if ($secchange) {
$$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
} else {
$$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
@@ -11865,7 +15305,7 @@ sub commit_studentrole {
$result = $modify_section_result;
} elsif ($secchange == 1) {
if ($oldsec eq '') {
- $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
+ $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
} else {
$$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
}
@@ -11891,6 +15331,26 @@ sub commit_studentrole {
return $result;
}
+sub show_role_extent {
+ my ($scope,$context,$role) = @_;
+ $scope =~ s{^/}{};
+ my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
+ push(@courseroles,'co');
+ my @authorroles = &Apache::lonuserutils::roles_by_context('author');
+ if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
+ $scope =~ s{/}{_};
+ return ''.$env{'course.'.$scope.'.description'}.'';
+ } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
+ my ($audom,$auname) = split(/\//,$scope);
+ return &mt('[_1] Author Space',''.
+ &Apache::loncommon::plainname($auname,$audom).'');
+ } else {
+ $scope =~ s{/$}{};
+ return &mt('Domain: [_1]',''.
+ &Apache::lonnet::domain($scope,'description').'');
+ }
+}
+
############################################################
############################################################
@@ -11915,42 +15375,100 @@ sub check_clone {
my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
if ($args->{'crstype'} eq 'Community') {
if ($clonedesc{'type'} ne 'Community') {
- $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
+ $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
return ($can_clone, $clonemsg, $cloneid, $clonehome);
}
}
- if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
+ if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
(&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
$can_clone = 1;
} else {
- my %clonehash = &Apache::lonnet::get('environment',['cloners'],
+ my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
$args->{'clonedomain'},$args->{'clonecourse'});
- my @cloners = split(/,/,$clonehash{'cloners'});
- if (grep(/^\*$/,@cloners)) {
- $can_clone = 1;
- } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
- $can_clone = 1;
+ if ($clonehash{'cloners'} eq '') {
+ my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
+ if ($domdefs{'canclone'}) {
+ unless ($domdefs{'canclone'} eq 'none') {
+ if ($domdefs{'canclone'} eq 'domain') {
+ if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
+ $can_clone = 1;
+ }
+ } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
+ ($args->{'clonedomain'} eq $args->{'course_domain'})) {
+ if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
+ $clonehash{'internal.coursecode'},$args->{'crscode'})) {
+ $can_clone = 1;
+ }
+ }
+ }
+ }
} else {
+ my @cloners = split(/,/,$clonehash{'cloners'});
+ if (grep(/^\*$/,@cloners)) {
+ $can_clone = 1;
+ } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
+ $can_clone = 1;
+ } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
+ $can_clone = 1;
+ }
+ unless ($can_clone) {
+ if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
+ ($args->{'clonedomain'} eq $args->{'course_domain'})) {
+ my (%gotdomdefaults,%gotcodedefaults);
+ foreach my $cloner (@cloners) {
+ if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
+ ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
+ my (%codedefaults,@code_order);
+ if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
+ if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
+ %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
+ }
+ if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
+ @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
+ }
+ } else {
+ &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
+ \%codedefaults,
+ \@code_order);
+ $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
+ $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
+ }
+ if (@code_order > 0) {
+ if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
+ $cloner,$clonehash{'internal.coursecode'},
+ $args->{'crscode'})) {
+ $can_clone = 1;
+ last;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ unless ($can_clone) {
my $ccrole = 'cc';
if ($args->{'crstype'} eq 'Community') {
$ccrole = 'co';
}
my %roleshash =
&Apache::lonnet::get_my_roles($args->{'ccuname'},
- $args->{'ccdomain'},
- 'userroles',['active'],[$ccrole],
- [$args->{'clonedomain'}]);
- if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
+ $args->{'ccdomain'},
+ 'userroles',['active'],[$ccrole],
+ [$args->{'clonedomain'}]);
+ if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
$can_clone = 1;
- } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
+ } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
+ $args->{'ccuname'},$args->{'ccdomain'})) {
$can_clone = 1;
+ }
+ }
+ unless ($can_clone) {
+ if ($args->{'crstype'} eq 'Community') {
+ $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
} else {
- if ($args->{'crstype'} eq 'Community') {
- $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
- } else {
- $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
- }
- }
+ $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
+ }
}
}
}
@@ -11958,7 +15476,8 @@ sub check_clone {
}
sub construct_course {
- my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
+ my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
+ $cnum,$category,$coderef) = @_;
my $outcome;
my $linefeed = ' '."\n";
if ($context eq 'auto') {
@@ -11986,7 +15505,12 @@ sub construct_course {
#
# Open course
#
- my $crstype = lc($args->{'crstype'});
+ my $showncrstype;
+ if ($args->{'crstype'} eq 'Placement') {
+ $showncrstype = 'placement test';
+ } else {
+ $showncrstype = lc($args->{'crstype'});
+ }
my %cenv=();
$$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
$args->{'cdescr'},
@@ -12003,7 +15527,7 @@ sub construct_course {
# Utils::Course. This needs to at least be output as a comment
# if anyone ever decides to not show this, and Utils::Course::new
# will need to be suitably modified.
- $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
+ $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
if ($$courseid =~ /^error:/) {
return (0,$outcome);
}
@@ -12023,7 +15547,7 @@ sub construct_course {
# Do the cloning
#
if ($can_clone && $cloneid) {
- $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
+ $clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
if ($context ne 'auto') {
$clonemsg = ''.$clonemsg.'';
}
@@ -12054,8 +15578,13 @@ sub construct_course {
'pch.users.denied',
'plc.users.denied',
'hidefromcat',
- 'categories'],
+ 'checkforpriv',
+ 'categories',
+ 'internal.uniquecode'],
$$crsudom,$$crsunum);
+ if ($args->{'textbook'}) {
+ $cenv{'internal.textbook'} = $args->{'textbook'};
+ }
}
#
@@ -12083,6 +15612,9 @@ sub construct_course {
} else {
$cenv{'internal.courseowner'} = $args->{'curruser'};
}
+ if ($args->{'defaultcredits'}) {
+ $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
+ }
my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
if ($args->{'crssections'}) {
$cenv{'internal.sectionnums'} = '';
@@ -12098,7 +15630,7 @@ sub construct_course {
my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
$cenv{'internal.sectionnums'} .= $item.',';
unless ($addcheck eq 'ok') {
- push @badclasses, $class;
+ push(@badclasses,$class);
}
}
$cenv{'internal.sectionnums'} =~ s/,$//;
@@ -12107,6 +15639,11 @@ sub construct_course {
# do not hide course coordinator from staff listing,
# even if privileged
$cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
+# add course coordinator's domain to domains to check for privileged users
+# if different to course domain
+ if ($$crsudom ne $args->{'ccdomain'}) {
+ $cenv{'checkforpriv'} = $args->{'ccdomain'};
+ }
# add crosslistings
if ($args->{'crsxlist'}) {
$cenv{'internal.crosslistings'}='';
@@ -12121,7 +15658,7 @@ sub construct_course {
my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
$cenv{'internal.crosslistings'} .= $item.',';
unless ($addcheck eq 'ok') {
- push @badclasses, $xl;
+ push(@badclasses,$xl);
}
}
$cenv{'internal.crosslistings'} =~ s/,$//;
@@ -12156,27 +15693,28 @@ sub construct_course {
}
if (@badclasses > 0) {
my %lt=&Apache::lonlocal::texthash(
- 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course. However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
- 'dnhr' => 'does not have rights to access enrollment in these classes',
- 'adby' => 'as determined by the policies of your institution on access to official classlists'
+ 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
+ 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
+ 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
);
- my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
- ' ('.$lt{'adby'}.')';
+ my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
+ &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
if ($context eq 'auto') {
$outcome .= $badclass_msg.$linefeed;
+ } else {
$outcome .= ''.$badclass_msg.$linefeed.' '."\n";
- foreach my $item (@badclasses) {
- if ($context eq 'auto') {
- $outcome .= " - $item\n";
- } else {
- $outcome .= "- $item
\n";
- }
- }
+ }
+ foreach my $item (@badclasses) {
if ($context eq 'auto') {
- $outcome .= $linefeed;
+ $outcome .= " - $item\n";
} else {
- $outcome .= " \n";
+ $outcome .= "- $item
\n";
}
+ }
+ if ($context eq 'auto') {
+ $outcome .= $linefeed;
+ } else {
+ $outcome .= "
\n";
}
}
if ($args->{'no_end_date'}) {
@@ -12209,6 +15747,9 @@ sub construct_course {
if ($args->{'setcontent'}) {
$cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
}
+ if ($args->{'setcomment'}) {
+ $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
+ }
}
if ($args->{'reshome'}) {
$cenv{'reshome'}=$args->{'reshome'}.'/';
@@ -12231,6 +15772,25 @@ sub construct_course {
}
}
+#
+# generate and store uniquecode (available to course requester), if course should have one.
+#
+ if ($args->{'uniquecode'}) {
+ my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
+ if ($code) {
+ $cenv{'internal.uniquecode'} = $code;
+ my %crsinfo =
+ &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
+ if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
+ $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
+ my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
+ }
+ if (ref($coderef)) {
+ $$coderef = $code;
+ }
+ }
+ }
+
if ($args->{'disresdis'}) {
$cenv{'pch.roles.denied'}='st';
}
@@ -12296,14 +15856,91 @@ sub construct_course {
$outcome .= ($fatal?$errtext:'write ok').$linefeed;
}
+#
+# Set params for Placement Tests
+#
+ if ($args->{'crstype'} eq 'Placement') {
+ my %storecontent;
+ my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
+ my %defaults = (
+ buttonshide => { value => 'yes',
+ type => 'string_yesno',},
+ type => { value => 'randomizetry',
+ type => 'string_questiontype',},
+ maxtries => { value => 1,
+ type => 'int_pos',},
+ problemstatus => { value => 'no',
+ type => 'string_problemstatus',},
+ );
+ foreach my $key (keys(%defaults)) {
+ $storecontent{$prefix.$key} = $defaults{$key}{'value'};
+ $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
+ }
+ &Apache::lonnet::cput
+ ('resourcedata',\%storecontent,$$crsudom,$$crsunum);
+ }
+
return (1,$outcome);
}
+sub make_unique_code {
+ my ($cdom,$cnum) = @_;
+ # get lock on uniquecodes db
+ my $lockhash = {
+ $cnum."\0".'uniquecodes' => $env{'user.name'}.
+ ':'.$env{'user.domain'},
+ };
+ my $tries = 0;
+ my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
+ my ($code,$error);
+
+ while (($gotlock ne 'ok') && ($tries<3)) {
+ $tries ++;
+ sleep 1;
+ $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
+ }
+ if ($gotlock eq 'ok') {
+ my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
+ my $gotcode;
+ my $attempts = 0;
+ while ((!$gotcode) && ($attempts < 100)) {
+ $code = &generate_code();
+ if (!exists($currcodes{$code})) {
+ $gotcode = 1;
+ unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
+ $error = 'nostore';
+ }
+ }
+ $attempts ++;
+ }
+ my @del_lock = ($cnum."\0".'uniquecodes');
+ my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
+ } else {
+ $error = 'nolock';
+ }
+ return ($code,$error);
+}
+
+sub generate_code {
+ my $code;
+ my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
+ for (my $i=0; $i<6; $i++) {
+ my $lettnum = int (rand 2);
+ my $item = '';
+ if ($lettnum) {
+ $item = $letts[int( rand(18) )];
+ } else {
+ $item = 1+int( rand(8) );
+ }
+ $code .= $item;
+ }
+ return $code;
+}
+
############################################################
############################################################
-#SD
-# only Community and Course, or anything else?
+# Community, Course and Placement Test
sub course_type {
my ($cid) = @_;
if (!defined($cid)) {
@@ -12321,16 +15958,19 @@ sub group_term {
my %names = (
'Course' => 'group',
'Community' => 'group',
+ 'Placement' => 'group',
);
return $names{$crstype};
}
sub course_types {
- my @types = ('official','unofficial','community');
+ my @types = ('official','unofficial','community','textbook','placement');
my %typename = (
official => 'Official course',
unofficial => 'Unofficial course',
community => 'Community',
+ textbook => 'Textbook course',
+ placement => 'Placement test',
);
return (\@types,\%typename);
}
@@ -12391,7 +16031,7 @@ sub escape_url {
my ($url) = @_;
my @urlslices = split(/\//, $url,-1);
my $lastitem = &escape(pop(@urlslices));
- return join('/',@urlslices).'/'.$lastitem;
+ return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
}
sub compare_arrays {
@@ -12417,9 +16057,7 @@ sub init_user_environment {
my $public=($username eq 'public' && $domain eq 'public');
-# See if old ID present, if so, remove
-
- my ($filename,$cookie,$userroles);
+ my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
my $now=time;
if ($public) {
@@ -12440,7 +16078,8 @@ sub init_user_environment {
}
if (!$cookie) { $cookie="publicuser_$oldest"; }
} else {
- # if this isn't a robot, kill any existing non-robot sessions
+ # See if old ID present, if so, remove if this isn't a robot,
+ # killing any existing non-robot sessions
if (!$args->{'robot'}) {
opendir(DIR,$lonids);
while ($filename=readdir(DIR)) {
@@ -12449,6 +16088,17 @@ sub init_user_environment {
}
}
closedir(DIR);
+# If there is a undeleted lockfile for the user's paste buffer remove it.
+ my $namespace = 'nohist_courseeditor';
+ my $lockingkey = 'paste'."\0".'locked_num';
+ my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
+ $domain,$username);
+ if (exists($lockhash{$lockingkey})) {
+ my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
+ unless ($delresult eq 'ok') {
+ &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
+ }
+ }
}
# Give them a new cookie
my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
@@ -12457,19 +16107,19 @@ sub init_user_environment {
# Initialize roles
- $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
+ ($userroles,$firstaccenv,$timerintenv) =
+ &Apache::lonnet::rolesinit($domain,$username,$authhost);
}
# ------------------------------------ Check browser type and MathML capability
- my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
- $clientunicode,$clientos) = &decode_user_agent($r);
+ my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
+ $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
# ------------------------------------------------------------- Get environment
my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
my ($tmp) = keys(%userenv);
- if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
- } else {
+ if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
undef(%userenv);
}
if (($userenv{'interface'}) && (!$form->{'interface'})) {
@@ -12493,6 +16143,9 @@ sub init_user_environment {
"browser.mathml" => $clientmathml,
"browser.unicode" => $clientunicode,
"browser.os" => $clientos,
+ "browser.mobile" => $clientmobile,
+ "browser.info" => $clientinfo,
+ "browser.osversion" => $clientosversion,
"server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
"request.course.fn" => '',
"request.course.uri" => '',
@@ -12512,32 +16165,94 @@ sub init_user_environment {
$env{'browser.interface'}=$form->{'interface'};
}
- my %is_adv = ( is_adv => $env{'user.adv'} );
- my %domdef;
- unless ($domain eq 'public') {
- %domdef = &Apache::lonnet::get_domain_defaults($domain);
+ if ($form->{'iptoken'}) {
+ my $lonhost = $r->dir_config('lonHostID');
+ $initial_env{"user.noloadbalance"} = $lonhost;
+ $env{'user.noloadbalance'} = $lonhost;
}
- foreach my $tool ('aboutme','blog','portfolio') {
- $userenv{'availabletools.'.$tool} =
- &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
- undef,\%userenv,\%domdef,\%is_adv);
+ if ($form->{'noloadbalance'}) {
+ my @hosts = &Apache::lonnet::current_machine_ids();
+ my $hosthere = $form->{'noloadbalance'};
+ if (grep(/^\Q$hosthere\E$/,@hosts)) {
+ $initial_env{"user.noloadbalance"} = $hosthere;
+ $env{'user.noloadbalance'} = $hosthere;
+ }
}
- foreach my $crstype ('official','unofficial','community') {
- $userenv{'canrequest.'.$crstype} =
- &Apache::lonnet::usertools_access($username,$domain,$crstype,
- 'reload','requestcourses',
+ unless ($domain eq 'public') {
+ my %is_adv = ( is_adv => $env{'user.adv'} );
+ my %domdef = &Apache::lonnet::get_domain_defaults($domain);
+
+ foreach my $tool ('aboutme','blog','webdav','portfolio') {
+ $userenv{'availabletools.'.$tool} =
+ &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
+ undef,\%userenv,\%domdef,\%is_adv);
+ }
+
+ foreach my $crstype ('official','unofficial','community','textbook','placement') {
+ $userenv{'canrequest.'.$crstype} =
+ &Apache::lonnet::usertools_access($username,$domain,$crstype,
+ 'reload','requestcourses',
+ \%userenv,\%domdef,\%is_adv);
+ }
+
+ $userenv{'canrequest.author'} =
+ &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
+ 'reload','requestauthor',
\%userenv,\%domdef,\%is_adv);
+ my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
+ $domain,$username);
+ my $reqstatus = $reqauthor{'author_status'};
+ if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
+ if (ref($reqauthor{'author'}) eq 'HASH') {
+ $userenv{'requestauthorqueued'} = $reqstatus.':'.
+ $reqauthor{'author'}{'timestamp'};
+ }
+ }
+ my ($types,$typename) = &course_types();
+ if (ref($types) eq 'ARRAY') {
+ my @options = ('approval','validate','autolimit');
+ my $optregex = join('|',@options);
+ my (%willtrust,%trustchecked);
+ foreach my $type (@{$types}) {
+ my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
+ if ($dom_str ne '') {
+ my $updatedstr = '';
+ my @possdomains = split(',',$dom_str);
+ foreach my $entry (@possdomains) {
+ my ($extdom,$extopt) = split(':',$entry);
+ unless ($trustchecked{$extdom}) {
+ $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
+ $trustchecked{$extdom} = 1;
+ }
+ if ($willtrust{$extdom}) {
+ $updatedstr .= $entry.',';
+ }
+ }
+ $updatedstr =~ s/,$//;
+ if ($updatedstr) {
+ $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
+ } else {
+ delete($userenv{'reqcrsotherdom.'.$type});
+ }
+ }
+ }
+ }
}
-
$env{'user.environment'} = "$lonids/$cookie.id";
-
+
if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
&GDBM_WRCREAT(),0640)) {
&_add_to_env(\%disk_env,\%initial_env);
&_add_to_env(\%disk_env,\%userenv,'environment.');
&_add_to_env(\%disk_env,$userroles);
+ if (ref($firstaccenv) eq 'HASH') {
+ &_add_to_env(\%disk_env,$firstaccenv);
+ }
+ if (ref($timerintenv) eq 'HASH') {
+ &_add_to_env(\%disk_env,$timerintenv);
+ }
if (ref($args->{'extra_env'})) {
&_add_to_env(\%disk_env,$args->{'extra_env'});
}
@@ -12573,7 +16288,9 @@ sub get_symb {
my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
if ($symb eq '') {
if (!$silent) {
- $request->print("Unable to handle ambiguous references:$url:.");
+ if (ref($request)) {
+ $request->print("Unable to handle ambiguous references:$url:.");
+ }
return ();
}
}
@@ -12607,42 +16324,1263 @@ sub clean_symb {
return ($symb,$enc);
}
-sub build_release_hashes {
- my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
- return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
- (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
- (ref($randomizetry) eq 'HASH'));
- foreach my $key (keys(%Apache::lonnet::needsrelease)) {
- my ($item,$name,$value) = split(/:/,$key);
- if ($item eq 'parameter') {
- if (ref($checkparms->{$name}) eq 'ARRAY') {
- unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
- push(@{$checkparms->{$name}},$value);
- }
+############################################################
+############################################################
+
+=pod
+
+=head1 Routines for building display used to search for courses
+
+
+=over 4
+
+=item * &build_filters()
+
+Create markup for a table used to set filters to use when selecting
+courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
+and quotacheck.pl
+
+
+Inputs:
+
+filterlist - anonymous array of fields to include as potential filters
+
+crstype - course type
+
+roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
+ to pop-open a course selector (will contain "extra element").
+
+multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
+
+filter - anonymous hash of criteria and their values
+
+action - form action
+
+numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
+
+caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
+
+cloneruname - username of owner of new course who wants to clone
+
+clonerudom - domain of owner of new course who wants to clone
+
+typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
+
+codetitlesref - reference to array of titles of components in institutional codes (official courses)
+
+codedom - domain
+
+formname - value of form element named "form".
+
+fixeddom - domain, if fixed.
+
+prevphase - value to assign to form element named "phase" when going back to the previous screen
+
+cnameelement - name of form element in form on opener page which will receive title of selected course
+
+cnumelement - name of form element in form on opener page which will receive courseID of selected course
+
+cdomelement - name of form element in form on opener page which will receive domain of selected course
+
+setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
+
+clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
+
+clonewarning - warning message about missing information for intended course owner when DC creates a course
+
+
+Returns: $output - HTML for display of search criteria, and hidden form elements.
+
+
+Side Effects: None
+
+=cut
+
+# ---------------------------------------------- search for courses based on last activity etc.
+
+sub build_filters {
+ my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
+ $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
+ $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
+ $cnameelement,$cnumelement,$cdomelement,$setroles,
+ $clonetext,$clonewarning) = @_;
+ my ($list,$jscript);
+ my $onchange = 'javascript:updateFilters(this)';
+ my ($domainselectform,$sincefilterform,$createdfilterform,
+ $ownerdomselectform,$persondomselectform,$instcodeform,
+ $typeselectform,$instcodetitle);
+ if ($formname eq '') {
+ $formname = $caller;
+ }
+ foreach my $item (@{$filterlist}) {
+ unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
+ ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
+ if ($item eq 'domainfilter') {
+ $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
+ } elsif ($item eq 'coursefilter') {
+ $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
+ } elsif ($item eq 'ownerfilter') {
+ $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
+ } elsif ($item eq 'ownerdomfilter') {
+ $filter->{'ownerdomfilter'} =
+ &LONCAPA::clean_domain($filter->{$item});
+ $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
+ 'ownerdomfilter',1);
+ } elsif ($item eq 'personfilter') {
+ $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
+ } elsif ($item eq 'persondomfilter') {
+ $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
+ 'persondomfilter',1);
} else {
- push(@{$checkparms->{$name}},$value);
+ $filter->{$item} =~ s/\W//g;
}
- } elsif ($item eq 'resourcetag') {
- if ($name eq 'responsetype') {
- $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
+ if (!$filter->{$item}) {
+ $filter->{$item} = '';
+ }
+ }
+ if ($item eq 'domainfilter') {
+ my $allow_blank = 1;
+ if ($formname eq 'portform') {
+ $allow_blank=0;
+ } elsif ($formname eq 'studentform') {
+ $allow_blank=0;
+ }
+ if ($fixeddom) {
+ $domainselectform = ''.
+ &Apache::lonnet::domain($codedom,'description');
+ } else {
+ $domainselectform = &select_dom_form($filter->{$item},
+ 'domainfilter',
+ $allow_blank,'',$onchange);
}
- } elsif ($item eq 'course') {
- if ($name eq 'crstype') {
- $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
+ } else {
+ $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
+ }
+ }
+
+ # last course activity filter and selection
+ $sincefilterform = &timebased_select_form('sincefilter',$filter);
+
+ # course created filter and selection
+ if (exists($filter->{'createdfilter'})) {
+ $createdfilterform = &timebased_select_form('createdfilter',$filter);
+ }
+
+ my $prefix = $crstype;
+ if ($crstype eq 'Placement') {
+ $prefix = 'Placement Test'
+ }
+ my %lt = &Apache::lonlocal::texthash(
+ 'cac' => "$prefix Activity",
+ 'ccr' => "$prefix Created",
+ 'cde' => "$prefix Title",
+ 'cdo' => "$prefix Domain",
+ 'ins' => 'Institutional Code',
+ 'inc' => 'Institutional Categorization',
+ 'cow' => "$prefix Owner/Co-owner",
+ 'cop' => "$prefix Personnel Includes",
+ 'cog' => 'Type',
+ );
+
+ if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
+ my $typeval = 'Course';
+ if ($crstype eq 'Community') {
+ $typeval = 'Community';
+ } elsif ($crstype eq 'Placement') {
+ $typeval = 'Placement';
+ }
+ $typeselectform = '';
+ } else {
+ $typeselectform = '";
+ }
+
+ my ($cloneableonlyform,$cloneabletitle);
+ if (exists($filter->{'cloneableonly'})) {
+ my $cloneableon = '';
+ my $cloneableoff = ' checked="checked"';
+ if ($filter->{'cloneableonly'}) {
+ $cloneableon = $cloneableoff;
+ $cloneableoff = '';
+ }
+ $cloneableonlyform = ''.(' 'x3).'';
+ if ($formname eq 'ccrs') {
+ $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
+ } else {
+ $cloneabletitle = &mt('Cloneable by you');
+ }
+ }
+ my $officialjs;
+ if ($crstype eq 'Course') {
+ if (exists($filter->{'instcodefilter'})) {
+# if (($fixeddom) || ($formname eq 'requestcrs') ||
+# ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
+ if ($codedom) {
+ $officialjs = 1;
+ ($instcodeform,$jscript,$$numtitlesref) =
+ &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
+ $officialjs,$codetitlesref);
+ if ($jscript) {
+ $jscript = ''."\n";
+ }
+ }
+ if ($instcodeform eq '') {
+ $instcodeform =
+ '';
+ $instcodetitle = $lt{'ins'};
+ } else {
+ $instcodetitle = $lt{'inc'};
+ }
+ if ($fixeddom) {
+ $instcodetitle .= ' ('.$codedom.')';
+ }
+ }
+ }
+ my $output = qq|
+'."\n".' '."\n";
+ return $jscript.$clonewarning.$output;
+}
+
+=pod
+
+=item * &timebased_select_form()
+
+Create markup for a dropdown list used to select a time-based
+filter e.g., Course Activity, Course Created, when searching for courses
+or communities
+
+Inputs:
+
+item - name of form element (sincefilter or createdfilter)
+
+filter - anonymous hash of criteria and their values
+
+Returns: HTML for a select box contained a blank, then six time selections,
+ with value set in incoming form variables currently selected.
+
+Side Effects: None
+
+=cut
+
+sub timebased_select_form {
+ my ($item,$filter) = @_;
+ if (ref($filter) eq 'HASH') {
+ $filter->{$item} =~ s/[^\d-]//g;
+ if (!$filter->{$item}) { $filter->{$item}=-1; }
+ return &select_form(
+ $filter->{$item},
+ $item,
+ { '-1' => '',
+ '86400' => &mt('today'),
+ '604800' => &mt('last week'),
+ '2592000' => &mt('last month'),
+ '7776000' => &mt('last three months'),
+ '15552000' => &mt('last six months'),
+ '31104000' => &mt('last year'),
+ 'select_form_order' =>
+ ['-1','86400','604800','2592000','7776000',
+ '15552000','31104000']});
+ }
+}
+
+=pod
+
+=item * &js_changer()
+
+Create script tag containing Javascript used to submit course search form
+when course type or domain is changed, and also to hide 'Searching ...' on
+page load completion for page showing search result.
+
+Inputs: None
+
+Returns: markup containing updateFilters() and hideSearching() javascript functions.
+
+Side Effects: None
+
+=cut
+
+sub js_changer {
+ return <
+// {major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
- ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
return;
}
+// ]]>
+
+
+ENDJS
+}
+
+=pod
+
+=item * &search_courses()
+
+Process selected filters form course search form and pass to lonnet::courseiddump
+to retrieve a hash for which keys are courseIDs which match the selected filters.
+
+Inputs:
+
+dom - domain being searched
+
+type - course type ('Course' or 'Community' or '.' if any).
+
+filter - anonymous hash of criteria and their values
+
+numtitles - for institutional codes - number of categories
+
+cloneruname - optional username of new course owner
+
+clonerudom - optional domain of new course owner
+
+domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
+ (used when DC is using course creation form)
+
+codetitles - reference to array of titles of components in institutional codes (official courses).
+
+cc_clone - escaped comma separated list of courses for which course cloner has active CC role
+ (and so can clone automatically)
+
+reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
+
+reqinstcode - institutional code of new course, where search_courses is used to identify potential
+ courses to clone
+
+Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
+
+
+Side Effects: None
+
+=cut
+
+
+sub search_courses {
+ my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
+ $cc_clone,$reqcrsdom,$reqinstcode) = @_;
+ my (%courses,%showcourses,$cloner);
+ if (($filter->{'ownerfilter'} ne '') ||
+ ($filter->{'ownerdomfilter'} ne '')) {
+ $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
+ $filter->{'ownerdomfilter'};
+ }
+ foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
+ if (!$filter->{$item}) {
+ $filter->{$item}='.';
+ }
+ }
+ my $now = time;
+ my $timefilter =
+ ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
+ my ($createdbefore,$createdafter);
+ if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
+ $createdbefore = $now;
+ $createdafter = $now-$filter->{'createdfilter'};
+ }
+ my ($instcodefilter,$regexpok);
+ if ($numtitles) {
+ if ($env{'form.official'} eq 'on') {
+ $instcodefilter =
+ &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
+ $regexpok = 1;
+ } elsif ($env{'form.official'} eq 'off') {
+ $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
+ unless ($instcodefilter eq '') {
+ $regexpok = -1;
+ }
+ }
+ } else {
+ $instcodefilter = $filter->{'instcodefilter'};
+ }
+ if ($instcodefilter eq '') { $instcodefilter = '.'; }
+ if ($type eq '') { $type = '.'; }
+
+ if (($clonerudom ne '') && ($cloneruname ne '')) {
+ $cloner = $cloneruname.':'.$clonerudom;
+ }
+ %courses = &Apache::lonnet::courseiddump($dom,
+ $filter->{'descriptfilter'},
+ $timefilter,
+ $instcodefilter,
+ $filter->{'combownerfilter'},
+ $filter->{'coursefilter'},
+ undef,undef,$type,$regexpok,undef,undef,
+ undef,undef,$cloner,$cc_clone,
+ $filter->{'cloneableonly'},
+ $createdbefore,$createdafter,undef,
+ $domcloner,undef,$reqcrsdom,$reqinstcode);
+ if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
+ my $ccrole;
+ if ($type eq 'Community') {
+ $ccrole = 'co';
+ } else {
+ $ccrole = 'cc';
+ }
+ my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
+ $filter->{'persondomfilter'},
+ 'userroles',undef,
+ [$ccrole,'in','ad','ep','ta','cr'],
+ $dom);
+ foreach my $role (keys(%rolehash)) {
+ my ($cnum,$cdom,$courserole) = split(':',$role);
+ my $cid = $cdom.'_'.$cnum;
+ if (exists($courses{$cid})) {
+ if (ref($courses{$cid}) eq 'HASH') {
+ if (ref($courses{$cid}{roles}) eq 'ARRAY') {
+ if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
+ push(@{$courses{$cid}{roles}},$courserole);
+ }
+ } else {
+ $courses{$cid}{roles} = [$courserole];
+ }
+ $showcourses{$cid} = $courses{$cid};
+ }
+ }
+ }
+ %courses = %showcourses;
+ }
+ return %courses;
+}
+
=pod
=back
+=head1 Routines for version requirements for current course.
+
+=over 4
+
+=item * &check_release_required()
+
+Compares required LON-CAPA version with version on server, and
+if required version is newer looks for a server with the required version.
+
+Looks first at servers in user's owen domain; if none suitable, looks at
+servers in course's domain are permitted to host sessions for user's domain.
+
+Inputs:
+
+$loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
+
+$courseid - Course ID of current course
+
+$rolecode - User's current role in course (for switchserver query string).
+
+$required - LON-CAPA version needed by course (format: Major.Minor).
+
+
+Returns:
+
+$switchserver - query string tp append to /adm/switchserver call (if
+ current server's LON-CAPA version is too old.
+
+$warning - Message is displayed if no suitable server could be found.
+
+=cut
+
+sub check_release_required {
+ my ($loncaparev,$courseid,$rolecode,$required) = @_;
+ my ($switchserver,$warning);
+ if ($required ne '') {
+ my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
+ my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
+ if ($reqdmajor ne '' && $reqdminor ne '') {
+ my $otherserver;
+ if (($major eq '' && $minor eq '') ||
+ (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
+ my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
+ my $switchlcrev =
+ &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
+ $userdomserver);
+ my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
+ if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
+ (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
+ my $cdom = $env{'course.'.$courseid.'.domain'};
+ if ($cdom ne $env{'user.domain'}) {
+ my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
+ my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
+ my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
+ my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
+ my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
+ my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
+ my $canhost =
+ &Apache::lonnet::can_host_session($env{'user.domain'},
+ $coursedomserver,
+ $remoterev,
+ $udomdefaults{'remotesessions'},
+ $defdomdefaults{'hostedsessions'});
+
+ if ($canhost) {
+ $otherserver = $coursedomserver;
+ } else {
+ $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).' '. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
+ }
+ } else {
+ $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).' '.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
+ }
+ } else {
+ $otherserver = $userdomserver;
+ }
+ }
+ if ($otherserver ne '') {
+ $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
+ }
+ }
+ }
+ return ($switchserver,$warning);
+}
+
+=pod
+
+=item * &check_release_result()
+
+Inputs:
+
+$switchwarning - Warning message if no suitable server found to host session.
+
+$switchserver - query string to append to /adm/switchserver containing lonHostID
+ and current role.
+
+Returns: HTML to display with information about requirement to switch server.
+ Either displaying warning with link to Roles/Courses screen or
+ display link to switchserver.
+
+=cut
+
+sub check_release_result {
+ my ($switchwarning,$switchserver) = @_;
+ my $output = &start_page('Selected course unavailable on this server').
+ '';
+ if ($switchwarning) {
+ $output .= $switchwarning.' ';
+ if (&show_course()) {
+ $output .= &mt('Display courses');
+ } else {
+ $output .= &mt('Display roles');
+ }
+ $output .= '';
+ } elsif ($switchserver) {
+ $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
+ ' '.
+ ''.
+ &mt('Switch Server').
+ '';
+ }
+ $output .= ' '.&end_page();
+ return $output;
+}
+
+=pod
+
+=item * &needs_coursereinit()
+
+Determine if course contents stored for user's session needs to be
+refreshed, because content has changed since "Big Hash" last tied.
+
+Check for change is made if time last checked is more than 10 minutes ago
+(by default).
+
+Inputs:
+
+$loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
+
+$interval (optional) - Time which may elapse (in s) between last check for content
+ change in current course. (default: 600 s).
+
+Returns: an array; first element is:
+
+=over 4
+
+'switch' - if content updates mean user's session
+ needs to be switched to a server running a newer LON-CAPA version
+
+'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
+ on current server hosting user's session
+
+'' - if no action required.
+
+=back
+
+If first item element is 'switch':
+
+second item is $switchwarning - Warning message if no suitable server found to host session.
+
+third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
+ and current role.
+
+otherwise: no other elements returned.
+
+=back
+
=cut
+sub needs_coursereinit {
+ my ($loncaparev,$interval) = @_;
+ return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
+ my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+ my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+ my $now = time;
+ if ($interval eq '') {
+ $interval = 600;
+ }
+ if (($now-$env{'request.course.timechecked'})>$interval) {
+ &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
+ my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
+ if ($blocked) {
+ return ();
+ }
+ my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
+ if ($lastchange > $env{'request.course.tied'}) {
+ my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
+ if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
+ my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
+ if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
+ &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
+ $curr_reqd_hash{'internal.releaserequired'}});
+ my ($switchserver,$switchwarning) =
+ &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
+ $curr_reqd_hash{'internal.releaserequired'});
+ if ($switchwarning ne '' || $switchserver ne '') {
+ return ('switch',$switchwarning,$switchserver);
+ }
+ }
+ }
+ return ('update');
+ }
+ }
+ return ();
+}
+
+sub update_content_constraints {
+ my ($cdom,$cnum,$chome,$cid) = @_;
+ my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
+ my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
+ my %checkresponsetypes;
+ foreach my $key (keys(%Apache::lonnet::needsrelease)) {
+ my ($item,$name,$value) = split(/:/,$key);
+ if ($item eq 'resourcetag') {
+ if ($name eq 'responsetype') {
+ $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
+ }
+ }
+ }
+ my $navmap = Apache::lonnavmaps::navmap->new();
+ if (defined($navmap)) {
+ my %allresponses;
+ foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
+ my %responses = $res->responseTypes();
+ foreach my $key (keys(%responses)) {
+ next unless(exists($checkresponsetypes{$key}));
+ $allresponses{$key} += $responses{$key};
+ }
+ }
+ foreach my $key (keys(%allresponses)) {
+ my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
+ if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
+ ($reqdmajor,$reqdminor) = ($major,$minor);
+ }
+ }
+ undef($navmap);
+ }
+ unless (($reqdmajor eq '') && ($reqdminor eq '')) {
+ &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
+ }
+ return;
+}
+
+sub allmaps_incourse {
+ my ($cdom,$cnum,$chome,$cid) = @_;
+ if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
+ $cid = $env{'request.course.id'};
+ $cdom = $env{'course.'.$cid.'.domain'};
+ $cnum = $env{'course.'.$cid.'.num'};
+ $chome = $env{'course.'.$cid.'.home'};
+ }
+ my %allmaps = ();
+ my $lastchange =
+ &Apache::lonnet::get_coursechange($cdom,$cnum);
+ if ($lastchange > $env{'request.course.tied'}) {
+ my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
+ unless ($ferr) {
+ &update_content_constraints($cdom,$cnum,$chome,$cid);
+ }
+ }
+ my $navmap = Apache::lonnavmaps::navmap->new();
+ if (defined($navmap)) {
+ foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
+ $allmaps{$res->src()} = 1;
+ }
+ }
+ return \%allmaps;
+}
+
+sub parse_supplemental_title {
+ my ($title) = @_;
+
+ my ($foldertitle,$renametitle);
+ if ($title =~ /&&&/) {
+ $title = &HTML::Entites::decode($title);
+ }
+ if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
+ $renametitle=$4;
+ my ($time,$uname,$udom) = ($1,$2,$3);
+ $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
+ my $name = &plainname($uname,$udom);
+ $name = &HTML::Entities::encode($name,'"<>&\'');
+ $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
+ $title=''.&Apache::lonlocal::locallocaltime($time).' '.
+ $name.': '.$foldertitle;
+ }
+ if (wantarray) {
+ return ($title,$foldertitle,$renametitle);
+ }
+ return $title;
+}
+
+sub recurse_supplemental {
+ my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
+ if ($suppmap) {
+ my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
+ if ($fatal) {
+ $errors ++;
+ } else {
+ if ($#LONCAPA::map::resources > 0) {
+ foreach my $res (@LONCAPA::map::resources) {
+ my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
+ if (($src ne '') && ($status eq 'res')) {
+ if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
+ ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
+ } else {
+ $numfiles ++;
+ }
+ }
+ }
+ }
+ }
+ }
+ return ($numfiles,$errors);
+}
+
+sub symb_to_docspath {
+ my ($symb,$navmapref) = @_;
+ return unless ($symb && ref($navmapref));
+ my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
+ if ($resurl=~/\.(sequence|page)$/) {
+ $mapurl=$resurl;
+ } elsif ($resurl eq 'adm/navmaps') {
+ $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
+ }
+ my $mapresobj;
+ unless (ref($$navmapref)) {
+ $$navmapref = Apache::lonnavmaps::navmap->new();
+ }
+ if (ref($$navmapref)) {
+ $mapresobj = $$navmapref->getResourceByUrl($mapurl);
+ }
+ $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
+ my $type=$2;
+ my $path;
+ if (ref($mapresobj)) {
+ my $pcslist = $mapresobj->map_hierarchy();
+ if ($pcslist ne '') {
+ foreach my $pc (split(/,/,$pcslist)) {
+ next if ($pc <= 1);
+ my $res = $$navmapref->getByMapPc($pc);
+ if (ref($res)) {
+ my $thisurl = $res->src();
+ $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
+ my $thistitle = $res->title();
+ $path .= '&'.
+ &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
+ &escape($thistitle).
+ ':'.$res->randompick().
+ ':'.$res->randomout().
+ ':'.$res->encrypted().
+ ':'.$res->randomorder().
+ ':'.$res->is_page();
+ }
+ }
+ }
+ $path =~ s/^\&//;
+ my $maptitle = $mapresobj->title();
+ if ($mapurl eq 'default') {
+ $maptitle = 'Main Content';
+ }
+ $path .= (($path ne '')? '&' : '').
+ &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
+ &escape($maptitle).
+ ':'.$mapresobj->randompick().
+ ':'.$mapresobj->randomout().
+ ':'.$mapresobj->encrypted().
+ ':'.$mapresobj->randomorder().
+ ':'.$mapresobj->is_page();
+ } else {
+ my $maptitle = &Apache::lonnet::gettitle($mapurl);
+ my $ispage = (($type eq 'page')? 1 : '');
+ if ($mapurl eq 'default') {
+ $maptitle = 'Main Content';
+ }
+ $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
+ &escape($maptitle).':::::'.$ispage;
+ }
+ unless ($mapurl eq 'default') {
+ $path = 'default&'.
+ &escape('Main Content').
+ ':::::&'.$path;
+ }
+ return $path;
+}
+
+sub captcha_display {
+ my ($context,$lonhost) = @_;
+ my ($output,$error);
+ my ($captcha,$pubkey,$privkey,$version) =
+ &get_captcha_config($context,$lonhost);
+ if ($captcha eq 'original') {
+ $output = &create_captcha();
+ unless ($output) {
+ $error = 'captcha';
+ }
+ } elsif ($captcha eq 'recaptcha') {
+ $output = &create_recaptcha($pubkey,$version);
+ unless ($output) {
+ $error = 'recaptcha';
+ }
+ }
+ return ($output,$error,$captcha,$version);
+}
+
+sub captcha_response {
+ my ($context,$lonhost) = @_;
+ my ($captcha_chk,$captcha_error);
+ my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
+ if ($captcha eq 'original') {
+ ($captcha_chk,$captcha_error) = &check_captcha();
+ } elsif ($captcha eq 'recaptcha') {
+ $captcha_chk = &check_recaptcha($privkey,$version);
+ } else {
+ $captcha_chk = 1;
+ }
+ return ($captcha_chk,$captcha_error);
+}
+
+sub get_captcha_config {
+ my ($context,$lonhost) = @_;
+ my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
+ my $hostname = &Apache::lonnet::hostname($lonhost);
+ my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
+ my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
+ if ($context eq 'usercreation') {
+ my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
+ if (ref($domconfig{$context}) eq 'HASH') {
+ $hashtocheck = $domconfig{$context}{'cancreate'};
+ if (ref($hashtocheck) eq 'HASH') {
+ if ($hashtocheck->{'captcha'} eq 'recaptcha') {
+ if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
+ $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
+ $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
+ }
+ if ($privkey && $pubkey) {
+ $captcha = 'recaptcha';
+ $version = $hashtocheck->{'recaptchaversion'};
+ if ($version ne '2') {
+ $version = 1;
+ }
+ } else {
+ $captcha = 'original';
+ }
+ } elsif ($hashtocheck->{'captcha'} ne 'notused') {
+ $captcha = 'original';
+ }
+ }
+ } else {
+ $captcha = 'captcha';
+ }
+ } elsif ($context eq 'login') {
+ my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
+ if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
+ $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
+ $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
+ if ($privkey && $pubkey) {
+ $captcha = 'recaptcha';
+ $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
+ if ($version ne '2') {
+ $version = 1;
+ }
+ } else {
+ $captcha = 'original';
+ }
+ } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
+ $captcha = 'original';
+ }
+ }
+ return ($captcha,$pubkey,$privkey,$version);
+}
+
+sub create_captcha {
+ my %captcha_params = &captcha_settings();
+ my ($output,$maxtries,$tries) = ('',10,0);
+ while ($tries < $maxtries) {
+ $tries ++;
+ my $captcha = Authen::Captcha->new (
+ output_folder => $captcha_params{'output_dir'},
+ data_folder => $captcha_params{'db_dir'},
+ );
+ my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
+
+ if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
+ $output = ''."\n".
+ &mt('Type in the letters/numbers shown below').' '.
+ ''.
+ ' '.
+ '';
+ last;
+ }
+ }
+ return $output;
+}
+
+sub captcha_settings {
+ my %captcha_params = (
+ output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
+ www_output_dir => "/captchaspool",
+ db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
+ numchars => '5',
+ );
+ return %captcha_params;
+}
+
+sub check_captcha {
+ my ($captcha_chk,$captcha_error);
+ my $code = $env{'form.code'};
+ my $md5sum = $env{'form.crypt'};
+ my %captcha_params = &captcha_settings();
+ my $captcha = Authen::Captcha->new(
+ output_folder => $captcha_params{'output_dir'},
+ data_folder => $captcha_params{'db_dir'},
+ );
+ $captcha_chk = $captcha->check_code($code,$md5sum);
+ my %captcha_hash = (
+ 0 => 'Code not checked (file error)',
+ -1 => 'Failed: code expired',
+ -2 => 'Failed: invalid code (not in database)',
+ -3 => 'Failed: invalid code (code does not match crypt)',
+ );
+ if ($captcha_chk != 1) {
+ $captcha_error = $captcha_hash{$captcha_chk}
+ }
+ return ($captcha_chk,$captcha_error);
+}
+
+sub create_recaptcha {
+ my ($pubkey,$version) = @_;
+ if ($version >= 2) {
+ return '';
+ } else {
+ my $use_ssl;
+ if ($ENV{'SERVER_PORT'} == 443) {
+ $use_ssl = 1;
+ }
+ my $captcha = Captcha::reCAPTCHA->new;
+ return $captcha->get_options_setter({theme => 'white'})."\n".
+ $captcha->get_html($pubkey,undef,$use_ssl).
+ &mt('If the text is hard to read, [_1] will replace them.',
+ '').
+ '
';
+ }
+}
+
+sub check_recaptcha {
+ my ($privkey,$version) = @_;
+ my $captcha_chk;
+ if ($version >= 2) {
+ my %info = (
+ secret => $privkey,
+ response => $env{'form.g-recaptcha-response'},
+ remoteip => $ENV{'REMOTE_ADDR'},
+ );
+ my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
+ $request->content(join('&',map {
+ my $name = escape($_);
+ "$name=" . ( ref($info{$_}) eq 'ARRAY'
+ ? join("&$name=", map {escape($_) } @{$info{$_}})
+ : &escape($info{$_}) );
+ } keys(%info)));
+ my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
+ if ($response->is_success) {
+ my $data = JSON::DWIW->from_json($response->decoded_content);
+ if (ref($data) eq 'HASH') {
+ if ($data->{'success'}) {
+ $captcha_chk = 1;
+ }
+ }
+ }
+ } else {
+ my $captcha = Captcha::reCAPTCHA->new;
+ my $captcha_result =
+ $captcha->check_answer(
+ $privkey,
+ $ENV{'REMOTE_ADDR'},
+ $env{'form.recaptcha_challenge_field'},
+ $env{'form.recaptcha_response_field'},
+ );
+ if ($captcha_result->{is_valid}) {
+ $captcha_chk = 1;
+ }
+ }
+ return $captcha_chk;
+}
+
+sub emailusername_info {
+ my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
+ my %titles = &Apache::lonlocal::texthash (
+ lastname => 'Last Name',
+ firstname => 'First Name',
+ institution => 'School/college/university',
+ location => "School's city, state/province, country",
+ web => "School's web address",
+ officialemail => 'E-mail address at institution (if different)',
+ id => 'Student/Employee ID',
+ );
+ return (\@fields,\%titles);
+}
+
+sub cleanup_html {
+ my ($incoming) = @_;
+ my $outgoing;
+ if ($incoming ne '') {
+ $outgoing = $incoming;
+ $outgoing =~ s/;/;/g;
+ $outgoing =~ s/\#/#/g;
+ $outgoing =~ s/\&/&/g;
+ $outgoing =~ s/</g;
+ $outgoing =~ s/>/>/g;
+ $outgoing =~ s/\(/(/g;
+ $outgoing =~ s/\)/)/g;
+ $outgoing =~ s/"/"/g;
+ $outgoing =~ s/'/'/g;
+ $outgoing =~ s/\$/$/g;
+ $outgoing =~ s{/}{/}g;
+ $outgoing =~ s/=/=/g;
+ $outgoing =~ s/\\/\/g
+ }
+ return $outgoing;
+}
+
+# Checks for critical messages and returns a redirect url if one exists.
+# $interval indicates how often to check for messages.
+# $context is the calling context -- roles, grades, contents, menu or flip.
+sub critical_redirect {
+ my ($interval,$context) = @_;
+ if ((time-$env{'user.criticalcheck.time'})>$interval) {
+ if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
+ my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+ my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+ my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
+ 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})) {
+ return;
+ }
+ }
+ }
+ my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
+ $env{'user.name'});
+ &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
+ my $redirecturl;
+ if ($what[0]) {
+ if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
+ $redirecturl='/adm/email?critical=display';
+ my $url=&Apache::lonnet::absolute_url().$redirecturl;
+ return (1, $url);
+ }
+ }
+ }
+ return ();
+}
+
+# Use:
+# my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
+#
+##################################################
+# password associated functions #
+##################################################
+sub des_keys {
+ # Make a new key for DES encryption.
+ # Each key has two parts which are returned separately.
+ # Please note: Each key must be passed through the &hex function
+ # before it is output to the web browser. The hex versions cannot
+ # be used to decrypt.
+ my @hexstr=('0','1','2','3','4','5','6','7',
+ '8','9','a','b','c','d','e','f');
+ my $lkey='';
+ for (0..7) {
+ $lkey.=$hexstr[rand(15)];
+ }
+ my $ukey='';
+ for (0..7) {
+ $ukey.=$hexstr[rand(15)];
+ }
+ return ($lkey,$ukey);
+}
+
+sub des_decrypt {
+ my ($key,$cyphertext) = @_;
+ my $keybin=pack("H16",$key);
+ my $cypher;
+ if ($Crypt::DES::VERSION>=2.03) {
+ $cypher=new Crypt::DES $keybin;
+ } else {
+ $cypher=new DES $keybin;
+ }
+ my $plaintext='';
+ my $cypherlength = length($cyphertext);
+ my $numchunks = int($cypherlength/32);
+ for (my $j=0; $j<$numchunks; $j++) {
+ my $start = $j*32;
+ my $cypherblock = substr($cyphertext,$start,32);
+ my $chunk =
+ $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
+ $chunk .=
+ $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
+ $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
+ $plaintext .= $chunk;
+ }
+ return $plaintext;
+}
+
1;
__END__;
| | |