+$nicescroll_js
+
+
+
END
}
@@ -7757,11 +8623,98 @@ sub end_scrollbox {
return '
';
}
+sub nicescroll_javascript {
+ my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
+ my %options;
+ if (ref($cursor) eq 'HASH') {
+ %options = %{$cursor};
+ }
+ unless ($options{'railalign'} =~ /^left|right$/) {
+ $options{'railalign'} = 'left';
+ }
+ unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
+ my $function = &get_users_function();
+ $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
+ unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
+ $options{'cursorcolor'} = '#00F';
+ }
+ }
+ if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
+ unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
+ $options{'cursoropacity'}='1.0';
+ }
+ } else {
+ $options{'cursoropacity'}='1.0';
+ }
+ if ($options{'cursorfixedheight'} eq 'none') {
+ delete($options{'cursorfixedheight'});
+ } else {
+ unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
+ }
+ unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
+ delete($options{'railoffset'});
+ }
+ my @niceoptions;
+ while (my($key,$value) = each(%options)) {
+ if ($value =~ /^\{.+\}$/) {
+ push(@niceoptions,$key.':'.$value);
+ } else {
+ push(@niceoptions,$key.':"'.$value.'"');
+ }
+ }
+ my $nicescroll_js = '
+$(document).ready(
+ function() {
+ $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
+ }
+);
+';
+ if ($framecheck) {
+ $nicescroll_js .= '
+function expand_div(caller) {
+ if (top === self) {
+ document.getElementById("'.$id.'").style.width = "auto";
+ document.getElementById("'.$id.'").style.height = "auto";
+ } else {
+ try {
+ if (parent.frames) {
+ if (parent.frames.length > 1) {
+ var framesrc = parent.frames[1].location.href;
+ var currsrc = framesrc.replace(/\#.*$/,"");
+ if ((caller == "search") || (currsrc == "'.$location.'")) {
+ document.getElementById("'.$id.'").style.width = "auto";
+ document.getElementById("'.$id.'").style.height = "auto";
+ }
+ }
+ }
+ } catch (e) {
+ return;
+ }
+ }
+ return;
+}
+';
+ }
+ if ($needjsready) {
+ $nicescroll_js = '
+\n";
+ } else {
+ $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
+ }
+ return $nicescroll_js;
+}
+
sub simple_error_page {
- my ($r,$title,$msg) = @_;
+ my ($r,$title,$msg,$args) = @_;
+ if (ref($args) eq 'HASH') {
+ if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
+ } else {
+ $msg = &mt($msg);
+ }
+
my $page =
&Apache::loncommon::start_page($title).
- &mt($msg).
+ '
'.$msg.'
'.
&Apache::loncommon::end_page();
if (ref($r)) {
$r->print($page);
@@ -7977,7 +8930,7 @@ role status: active, previous or future.
sub check_user_status {
my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
- my @uroles = keys %userinfo;
+ my @uroles = keys(%userinfo);
my $srchstr;
my $active_chk = 'none';
my $now = time;
@@ -8054,7 +9007,19 @@ sub get_sections {
my %sectioncount;
my $now = time;
- if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
+ my $check_students = 1;
+ my $only_students = 0;
+ if (ref($possible_roles) eq 'ARRAY') {
+ if (grep(/^st$/,@{$possible_roles})) {
+ if (@{$possible_roles} == 1) {
+ $only_students = 1;
+ }
+ } else {
+ $check_students = 0;
+ }
+ }
+
+ if ($check_students) {
my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
my $sec_index = &Apache::loncoursedata::CL_SECTION();
my $status_index = &Apache::loncoursedata::CL_STATUS();
@@ -8081,6 +9046,9 @@ sub get_sections {
}
}
}
+ if ($only_students) {
+ return %sectioncount;
+ }
my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
foreach my $user (sort(keys(%courseroles))) {
if ($user !~ /^(\w{2})/) { next; }
@@ -8228,7 +9196,7 @@ sub get_course_users {
active => 'Active',
future => 'Future',
);
- my %nothide;
+ my (%nothide,@possdoms);
if ($hidepriv) {
my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
@@ -8238,6 +9206,10 @@ sub get_course_users {
$nothide{$user} = 1;
}
}
+ my @possdoms = ($cdom);
+ if ($coursehash{'checkforpriv'}) {
+ push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
+ }
}
foreach my $person (sort(keys(%coursepersonnel))) {
my $match = 0;
@@ -8273,7 +9245,7 @@ sub get_course_users {
}
if ($uname ne '' && $udom ne '') {
if ($hidepriv) {
- if ((&Apache::lonnet::privileged($uname,$udom)) &&
+ if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
(!$nothide{$uname.':'.$udom})) {
next;
}
@@ -8361,14 +9333,19 @@ sub get_user_info {
=item * &get_user_quota()
-Retrieves quota assigned for storage of portfolio files for a user
+Retrieves quota assigned for storage of user files.
+Default is to report quota for portfolio files.
Incoming parameters:
1. user's username
2. user's domain
+3. quota name - portfolio, author, or course
+ (if no quota name provided, defaults to portfolio).
+4. crstype - official, unofficial, textbook or community, if quota name is
+ course
Returns:
-1. Disk quota (in Mb) assigned to student.
+1. Disk quota (in MB) assigned to student.
2. (Optional) Type of setting: custom or default
(individually assigned or default for user's
institutional status).
@@ -8379,7 +9356,7 @@ Returns:
If a value has been stored in the user's environment,
it will return that, otherwise it returns the maximal default
-defined for the user's instituional status(es) in the domain.
+defined for the user's institutional status(es) in the domain.
=cut
@@ -8387,7 +9364,7 @@ defined for the user's instituional stat
sub get_user_quota {
- my ($uname,$udom) = @_;
+ my ($uname,$udom,$quotaname,$crstype) = @_;
my ($quota,$quotatype,$settingstatus,$defquota);
if (!defined($udom)) {
$udom = $env{'user.domain'};
@@ -8402,27 +9379,58 @@ sub get_user_quota {
$defquota = 0;
} else {
my $inststatus;
- if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
- $quota = $env{'environment.portfolioquota'};
- $inststatus = $env{'environment.inststatus'};
- } else {
- my %userenv =
- &Apache::lonnet::get('environment',['portfolioquota',
- 'inststatus'],$udom,$uname);
- my ($tmp) = keys(%userenv);
- if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
- $quota = $userenv{'portfolioquota'};
- $inststatus = $userenv{'inststatus'};
- } else {
- undef(%userenv);
- }
- }
- ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
- if ($quota eq '') {
- $quota = $defquota;
- $quotatype = 'default';
+ if ($quotaname eq 'course') {
+ if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
+ ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
+ $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
+ } else {
+ my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
+ $quota = $cenv{'internal.uploadquota'};
+ }
} else {
- $quotatype = 'custom';
+ if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
+ if ($quotaname eq 'author') {
+ $quota = $env{'environment.authorquota'};
+ } else {
+ $quota = $env{'environment.portfolioquota'};
+ }
+ $inststatus = $env{'environment.inststatus'};
+ } else {
+ my %userenv =
+ &Apache::lonnet::get('environment',['portfolioquota',
+ 'authorquota','inststatus'],$udom,$uname);
+ my ($tmp) = keys(%userenv);
+ if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
+ if ($quotaname eq 'author') {
+ $quota = $userenv{'authorquota'};
+ } else {
+ $quota = $userenv{'portfolioquota'};
+ }
+ $inststatus = $userenv{'inststatus'};
+ } else {
+ undef(%userenv);
+ }
+ }
+ }
+ if ($quota eq '' || wantarray) {
+ if ($quotaname eq 'course') {
+ my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
+ if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
+ ($crstype eq 'community') || ($crstype eq 'textbook')) {
+ $defquota = $domdefs{$crstype.'quota'};
+ }
+ if ($defquota eq '') {
+ $defquota = 500;
+ }
+ } else {
+ ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
+ }
+ if ($quota eq '') {
+ $quota = $defquota;
+ $quotatype = 'default';
+ } else {
+ $quotatype = 'custom';
+ }
}
}
if (wantarray) {
@@ -8442,54 +9450,60 @@ Retrieves default quota assigned for sto
given an (optional) user's institutional status.
Incoming parameters:
+
1. domain
2. (Optional) institutional status(es). This is a : separated list of
status types (e.g., faculty, staff, student etc.)
which apply to the user for whom the default is being retrieved.
If the institutional status string in undefined, the domain
- default quota will be returned.
+ default quota will be returned.
+3. quota name - portfolio, author, or course
+ (if no quota name provided, defaults to portfolio).
Returns:
-1. Default disk quota (in Mb) for user portfolios in the domain.
+
+1. Default disk quota (in MB) for user portfolios in the domain.
2. (Optional) institutional type which determined the value of the
default quota.
If a value has been stored in the domain's configuration db,
it will return that, otherwise it returns 20 (for backwards
compatibility with domains which have not set up a configuration
-db file; the original statically defined portfolio quota was 20 Mb).
+db file; the original statically defined portfolio quota was 20 MB).
If the user's status includes multiple types (e.g., staff and student),
the largest default quota which applies to the user determines the
default quota returned.
-=back
-
=cut
###############################################
sub default_quota {
- my ($udom,$inststatus) = @_;
+ my ($udom,$inststatus,$quotaname) = @_;
my ($defquota,$settingstatus);
my %quotahash = &Apache::lonnet::get_dom('configuration',
['quotas'],$udom);
+ my $key = 'defaultquota';
+ if ($quotaname eq 'author') {
+ $key = 'authorquota';
+ }
if (ref($quotahash{'quotas'}) eq 'HASH') {
if ($inststatus ne '') {
my @statuses = map { &unescape($_); } split(/:/,$inststatus);
foreach my $item (@statuses) {
- if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
- if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
+ if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
+ if ($quotahash{'quotas'}{$key}{$item} ne '') {
if ($defquota eq '') {
- $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
+ $defquota = $quotahash{'quotas'}{$key}{$item};
$settingstatus = $item;
- } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
- $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
+ } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
+ $defquota = $quotahash{'quotas'}{$key}{$item};
$settingstatus = $item;
}
}
- } else {
+ } elsif ($key eq 'defaultquota') {
if ($quotahash{'quotas'}{$item} ne '') {
if ($defquota eq '') {
$defquota = $quotahash{'quotas'}{$item};
@@ -8503,16 +9517,25 @@ sub default_quota {
}
}
if ($defquota eq '') {
- if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
- $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
- } else {
+ if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
+ $defquota = $quotahash{'quotas'}{$key}{'default'};
+ } elsif ($key eq 'defaultquota') {
$defquota = $quotahash{'quotas'}{'default'};
}
$settingstatus = 'default';
+ if ($defquota eq '') {
+ if ($quotaname eq 'author') {
+ $defquota = 500;
+ }
+ }
}
} else {
$settingstatus = 'default';
- $defquota = 20;
+ if ($quotaname eq 'author') {
+ $defquota = 500;
+ } else {
+ $defquota = 20;
+ }
}
if (wantarray) {
return ($defquota,$settingstatus);
@@ -8521,6 +9544,62 @@ sub default_quota {
}
}
+###############################################
+
+=pod
+
+=item * &excess_filesize_warning()
+
+Returns warning message if upload of file to authoring space, or copying
+of existing file within authoring space will cause quota for the authoring
+space to be exceeded.
+
+Same, if upload of a file directly to a course/community via Course Editor
+will cause quota for uploaded content for the course to be exceeded.
+
+Inputs: 7
+1. username or coursenum
+2. domain
+3. context ('author' or 'course')
+4. filename of file for which action is being requested
+5. filesize (kB) of file
+6. action being taken: copy or upload.
+7. quotatype (in course context -- official, unofficial, community or textbook).
+
+Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
+ otherwise return null.
+
+=back
+
+=cut
+
+sub excess_filesize_warning {
+ my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
+ my $current_disk_usage = 0;
+ my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
+ if ($context eq 'author') {
+ my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
+ $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
+ } else {
+ foreach my $subdir ('docs','supplemental') {
+ $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
+ }
+ }
+ $disk_quota = int($disk_quota * 1000);
+ if (($current_disk_usage + $filesize) > $disk_quota) {
+ return '
'.
+ &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
+ ''.$filename.' ',$filesize).'
'.
+ '
'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
+ $disk_quota,$current_disk_usage).
+ '
';
+ }
+ return;
+}
+
+###############################################
+
+
sub get_secgrprole_info {
my ($cdom,$cnum,$needroles,$type) = @_;
my %sections_count = &get_sections($cdom,$cnum);
@@ -8559,8 +9638,24 @@ sub get_secgrprole_info {
}
sub user_picker {
- my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
+ my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
my $currdom = $dom;
+ my @alldoms = &Apache::lonnet::all_domains();
+ if (@alldoms == 1) {
+ my %domsrch = &Apache::lonnet::get_dom('configuration',
+ ['directorysrch'],$alldoms[0]);
+ my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
+ my $showdom = $domdesc;
+ if ($showdom eq '') {
+ $showdom = $dom;
+ }
+ if (ref($domsrch{'directorysrch'}) eq 'HASH') {
+ if ((!$domsrch{'directorysrch'}{'available'}) &&
+ ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
+ return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
+ }
+ }
+ }
my %curr_selected = (
srchin => 'dom',
srchby => 'lastname',
@@ -8581,7 +9676,7 @@ sub user_picker {
}
$srchterm = $srch->{'srchterm'};
}
- my %lt=&Apache::lonlocal::texthash(
+ my %html_lt=&Apache::lonlocal::texthash(
'usr' => 'Search criteria',
'doma' => 'Domain/institution to search',
'uname' => 'username',
@@ -8594,6 +9689,8 @@ sub user_picker {
'exact' => 'is',
'contains' => 'contains',
'begins' => 'begins with',
+ );
+ my %js_lt=&Apache::lonlocal::texthash(
'youm' => "You must include some text to search for.",
'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
@@ -8603,7 +9700,16 @@ sub user_picker {
'whse' => "When searching by last,first you must include at least one character in the first name.",
'thfo' => "The following need to be corrected before the search can be run:",
);
- my $domform = &select_dom_form($currdom,'srchdomain',1,1);
+ &html_escape(\%html_lt);
+ &js_escape(\%js_lt);
+ my $domform;
+ my $allow_blank = 1;
+ if ($fixeddom) {
+ $allow_blank = 0;
+ $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
+ } else {
+ $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
+ }
my $srchinsel = '
';
my @srchins = ('crs','dom','alc','instd');
@@ -8615,12 +9721,13 @@ sub user_picker {
next if ($option eq 'alc');
next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
next if ($option eq 'crs' && !$env{'request.course.id'});
+ next if (($option eq 'instd') && ($noinstd));
if ($curr_selected{'srchin'} eq $option) {
$srchinsel .= '
- '.$lt{$option}.' ';
+ '.$html_lt{$option}.' ';
} else {
$srchinsel .= '
- '.$lt{$option}.' ';
+ '.$html_lt{$option}.' ';
}
}
$srchinsel .= "\n \n";
@@ -8629,10 +9736,10 @@ sub user_picker {
foreach my $option ('lastname','lastfirst','uname') {
if ($curr_selected{'srchby'} eq $option) {
$srchbysel .= '
-
'.$lt{$option}.' ';
+
'.$html_lt{$option}.' ';
} else {
$srchbysel .= '
-
'.$lt{$option}.' ';
+
'.$html_lt{$option}.' ';
}
}
$srchbysel .= "\n \n";
@@ -8641,10 +9748,10 @@ sub user_picker {
foreach my $option ('begins','contains','exact') {
if ($curr_selected{'srchtype'} eq $option) {
$srchtypesel .= '
-
'.$lt{$option}.' ';
+
'.$html_lt{$option}.' ';
} else {
$srchtypesel .= '
-
'.$lt{$option}.' ';
+
'.$html_lt{$option}.' ';
}
}
$srchtypesel .= "\n \n";
@@ -8729,46 +9836,46 @@ function validateEntry(callingForm) {
if (srchterm == "") {
checkok = 0;
- msg += "$lt{'youm'}\\n";
+ msg += "$js_lt{'youm'}\\n";
}
if (srchtype== 'begins') {
if (srchterm.length < 2) {
checkok = 0;
- msg += "$lt{'thte'}\\n";
+ msg += "$js_lt{'thte'}\\n";
}
}
if (srchtype== 'contains') {
if (srchterm.length < 3) {
checkok = 0;
- msg += "$lt{'thet'}\\n";
+ msg += "$js_lt{'thet'}\\n";
}
}
if (srchin == 'instd') {
if (srchdomain == '') {
checkok = 0;
- msg += "$lt{'yomc'}\\n";
+ msg += "$js_lt{'yomc'}\\n";
}
}
if (srchin == 'dom') {
if (srchdomain == '') {
checkok = 0;
- msg += "$lt{'ymcd'}\\n";
+ msg += "$js_lt{'ymcd'}\\n";
}
}
if (srchby == 'lastfirst') {
if (srchterm.indexOf(",") == -1) {
checkok = 0;
- msg += "$lt{'whus'}\\n";
+ msg += "$js_lt{'whus'}\\n";
}
if (srchterm.indexOf(",") == srchterm.length -1) {
checkok = 0;
- msg += "$lt{'whse'}\\n";
+ msg += "$js_lt{'whse'}\\n";
}
}
if (checkok == 0) {
- alert("$lt{'thfo'}\\n"+msg);
+ alert("$js_lt{'thfo'}\\n"+msg);
return;
}
if (checkok == 1) {
@@ -8786,10 +9893,10 @@ $new_user_create
END_BLOCK
$output .= &Apache::lonhtmlcommon::start_pick_box().
- &Apache::lonhtmlcommon::row_title($lt{'doma'}).
+ &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
$domform.
&Apache::lonhtmlcommon::row_closure().
- &Apache::lonhtmlcommon::row_title($lt{'usr'}).
+ &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
$srchbysel.
$srchtypesel.
'
'.
@@ -8797,61 +9904,165 @@ END_BLOCK
&Apache::lonhtmlcommon::row_closure(1).
&Apache::lonhtmlcommon::end_pick_box().
'
';
- return $output;
+ return ($output,1);
}
sub user_rule_check {
my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
- my $response;
+ my ($response,%inst_response);
if (ref($usershash) eq 'HASH') {
- foreach my $user (keys(%{$usershash})) {
- my ($uname,$udom) = split(/:/,$user);
- next if ($udom eq '' || $uname eq '');
- my ($id,$newuser);
- if (ref($usershash->{$user}) eq 'HASH') {
- $newuser = $usershash->{$user}->{'newuser'};
- $id = $usershash->{$user}->{'id'};
- }
- my $inst_response;
+ if (keys(%{$usershash}) > 1) {
+ my (%by_username,%by_id,%userdoms);
+ my $checkid;
if (ref($checks) eq 'HASH') {
- if (defined($checks->{'username'})) {
- ($inst_response,%{$inst_results->{$user}}) =
- &Apache::lonnet::get_instuser($udom,$uname);
- } elsif (defined($checks->{'id'})) {
- ($inst_response,%{$inst_results->{$user}}) =
- &Apache::lonnet::get_instuser($udom,undef,$id);
+ if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
+ $checkid = 1;
+ }
+ }
+ foreach my $user (keys(%{$usershash})) {
+ my ($uname,$udom) = split(/:/,$user);
+ if ($checkid) {
+ if (ref($usershash->{$user}) eq 'HASH') {
+ if ($usershash->{$user}->{'id'} ne '') {
+ $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
+ $userdoms{$udom} = 1;
+ if (ref($inst_results) eq 'HASH') {
+ $inst_results->{$uname.':'.$udom} = {};
+ }
+ }
+ }
+ } else {
+ $by_username{$udom}{$uname} = 1;
+ $userdoms{$udom} = 1;
+ if (ref($inst_results) eq 'HASH') {
+ $inst_results->{$uname.':'.$udom} = {};
+ }
+ }
+ }
+ foreach my $udom (keys(%userdoms)) {
+ if (!$got_rules->{$udom}) {
+ my %domconfig = &Apache::lonnet::get_dom('configuration',
+ ['usercreation'],$udom);
+ if (ref($domconfig{'usercreation'}) eq 'HASH') {
+ foreach my $item ('username','id') {
+ if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
+ $$curr_rules{$udom}{$item} =
+ $domconfig{'usercreation'}{$item.'_rule'};
+ }
+ }
+ }
+ $got_rules->{$udom} = 1;
+ }
+ }
+ if ($checkid) {
+ foreach my $udom (keys(%by_id)) {
+ my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
+ if ($outcome eq 'ok') {
+ foreach my $id (keys(%{$by_id{$udom}})) {
+ my $uname = $by_id{$udom}{$id};
+ $inst_response{$uname.':'.$udom} = $outcome;
+ }
+ if (ref($results) eq 'HASH') {
+ foreach my $uname (keys(%{$results})) {
+ if (exists($inst_response{$uname.':'.$udom})) {
+ $inst_response{$uname.':'.$udom} = $outcome;
+ $inst_results->{$uname.':'.$udom} = $results->{$uname};
+ }
+ }
+ }
+ }
}
} else {
- ($inst_response,%{$inst_results->{$user}}) =
- &Apache::lonnet::get_instuser($udom,$uname);
- return;
+ foreach my $udom (keys(%by_username)) {
+ my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
+ if ($outcome eq 'ok') {
+ foreach my $uname (keys(%{$by_username{$udom}})) {
+ $inst_response{$uname.':'.$udom} = $outcome;
+ }
+ if (ref($results) eq 'HASH') {
+ foreach my $uname (keys(%{$results})) {
+ $inst_results->{$uname.':'.$udom} = $results->{$uname};
+ }
+ }
+ }
+ }
}
- if (!$got_rules->{$udom}) {
- my %domconfig = &Apache::lonnet::get_dom('configuration',
- ['usercreation'],$udom);
- if (ref($domconfig{'usercreation'}) eq 'HASH') {
- foreach my $item ('username','id') {
- if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
- $$curr_rules{$udom}{$item} =
- $domconfig{'usercreation'}{$item.'_rule'};
+ } elsif (keys(%{$usershash}) == 1) {
+ my $user = (keys(%{$usershash}))[0];
+ my ($uname,$udom) = split(/:/,$user);
+ if (($udom ne '') && ($uname ne '')) {
+ if (ref($usershash->{$user}) eq 'HASH') {
+ if (ref($checks) eq 'HASH') {
+ if (defined($checks->{'username'})) {
+ ($inst_response{$user},%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,$uname);
+ } elsif (defined($checks->{'id'})) {
+ if ($usershash->{$user}->{'id'} ne '') {
+ ($inst_response{$user},%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,undef,
+ $usershash->{$user}->{'id'});
+ } else {
+ ($inst_response{$user},%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,$uname);
+ }
+ }
+ } else {
+ ($inst_response{$user},%{$inst_results->{$user}}) =
+ &Apache::lonnet::get_instuser($udom,$uname);
+ return;
+ }
+ if (!$got_rules->{$udom}) {
+ my %domconfig = &Apache::lonnet::get_dom('configuration',
+ ['usercreation'],$udom);
+ if (ref($domconfig{'usercreation'}) eq 'HASH') {
+ foreach my $item ('username','id') {
+ if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
+ $$curr_rules{$udom}{$item} =
+ $domconfig{'usercreation'}{$item.'_rule'};
+ }
+ }
}
+ $got_rules->{$udom} = 1;
}
}
- $got_rules->{$udom} = 1;
+ } else {
+ return;
+ }
+ } else {
+ return;
+ }
+ foreach my $user (keys(%{$usershash})) {
+ my ($uname,$udom) = split(/:/,$user);
+ next if (($udom eq '') || ($uname eq ''));
+ my $id;
+ if (ref($inst_results) eq 'HASH') {
+ if (ref($inst_results->{$user}) eq 'HASH') {
+ $id = $inst_results->{$user}->{'id'};
+ }
+ }
+ if ($id eq '') {
+ if (ref($usershash->{$user})) {
+ $id = $usershash->{$user}->{'id'};
+ }
}
foreach my $item (keys(%{$checks})) {
if (ref($$curr_rules{$udom}) eq 'HASH') {
if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
if (@{$$curr_rules{$udom}{$item}} > 0) {
- my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
+ my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
+ $$curr_rules{$udom}{$item});
foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
if ($rule_check{$rule}) {
$$rulematch{$user}{$item} = $rule;
- if ($inst_response eq 'ok') {
+ if ($inst_response{$user} eq 'ok') {
if (ref($inst_results) eq 'HASH') {
if (ref($inst_results->{$user}) eq 'HASH') {
if (keys(%{$inst_results->{$user}}) == 0) {
$$alerts{$item}{$udom}{$uname} = 1;
+ } elsif ($item eq 'id') {
+ if ($inst_results->{$user}->{'id'} eq '') {
+ $$alerts{$item}{$udom}{$uname} = 1;
+ }
}
}
}
@@ -8878,7 +10089,10 @@ sub user_rule_formats {
my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
if (@{$ruleorder} > 0) {
- $output = '
'.&mt("$text{$check} with the following format(s) may
only be used for verified users at [_1]:",$domdesc).'
';
+ $output = ' '.
+ &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
+ '',' ',$domdesc).
+ ' ';
foreach my $rule (@{$ruleorder}) {
if (ref($curr_rules) eq 'ARRAY') {
if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
@@ -8959,7 +10173,14 @@ sub personal_data_fieldtitles {
sub sorted_inst_types {
my ($dom) = @_;
- my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
+ my ($usertypes,$order);
+ my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
+ if (ref($domdefaults{'inststatus'}) eq 'HASH') {
+ $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
+ $order = $domdefaults{'inststatus'}{'inststatusorder'};
+ } else {
+ ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
+ }
my $othertitle = &mt('All users');
if ($env{'request.course.id'}) {
$othertitle = &mt('Any users');
@@ -8998,7 +10219,7 @@ sub get_institutional_codes {
foreach (@currxlists) {
if (m/^([^:]+):(\w*)$/) {
unless (grep/^$1$/,@{$allcourses}) {
- push @{$allcourses},$1;
+ push(@{$allcourses},$1);
$$LC_code{$1} = $2;
}
}
@@ -9011,7 +10232,7 @@ sub get_institutional_codes {
my $sec = $coursecode.$1;
my $lc_sec = $2;
unless (grep/^$sec$/,@{$allcourses}) {
- push @{$allcourses},$sec;
+ push(@{$allcourses},$sec);
$$LC_code{$sec} = $lc_sec;
}
}
@@ -9109,7 +10330,9 @@ reservable_now - ref to hash of student_
Keys in inner hash are:
(a) symb: either blank or symb to which slot use is restricted.
- (b) endreserve: end date of reservation period.
+ (b) endreserve: end date of reservation period.
+ (c) uniqueperiod: start,end dates when slot is to be uniquely
+ selected.
sorted_future - ref to array of student_schedulable slots reservable in
the future, ordered by start date of reservation period.
@@ -9120,6 +10343,8 @@ future_reservable - ref to hash of stude
Keys in inner hash are:
(a) symb: either blank or symb to which slot use is restricted.
(b) startreserve: start date of reservation period.
+ (c) uniqueperiod: start,end dates when slot is to be uniquely
+ selected.
=back
@@ -9173,6 +10398,10 @@ sub get_future_slots {
my $startreserve = $slots{$slot}->{'startreserve'};
my $endreserve = $slots{$slot}->{'endreserve'};
my $symb = $slots{$slot}->{'symb'};
+ my $uniqueperiod;
+ if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
+ $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
+ }
if (($startreserve < $now) &&
(!$endreserve || $endreserve > $now)) {
my $lastres = $endreserve;
@@ -9181,13 +10410,15 @@ sub get_future_slots {
}
$reservable_now{$slot} = {
symb => $symb,
- endreserve => $lastres
+ endreserve => $lastres,
+ uniqueperiod => $uniqueperiod,
};
} elsif (($startreserve > $now) &&
(!$endreserve || $endreserve > $startreserve)) {
$future_reservable{$slot} = {
symb => $symb,
- startreserve => $startreserve
+ startreserve => $startreserve,
+ uniqueperiod => $uniqueperiod,
};
}
}
@@ -9348,7 +10579,7 @@ sub get_env_multiple {
sub ask_for_embedded_content {
my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
- %currsubfile,%unused);
+ %currsubfile,%unused,$rem);
my $counter = 0;
my $numnew = 0;
my $numremref = 0;
@@ -9357,18 +10588,26 @@ sub ask_for_embedded_content {
my $numexisting = 0;
my $numunused = 0;
my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
- $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
+ $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
my $heading = &mt('Upload embedded files');
my $buttontext = &mt('Upload');
- if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
+ if ($env{'request.course.id'}) {
+ if ($actionurl eq '/adm/dependencies') {
+ $navmap = Apache::lonnavmaps::navmap->new();
+ }
+ $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+ $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+ }
+ if (($actionurl eq '/adm/portfolio') ||
+ ($actionurl eq '/adm/coursegrp_portfolio')) {
my $current_path='/';
if ($env{'form.currentpath'}) {
$current_path = $env{'form.currentpath'};
}
if ($actionurl eq '/adm/coursegrp_portfolio') {
- $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
- $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
+ $udom = $cdom;
+ $uname = $cnum;
$url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
} else {
$udom = $env{'user.domain'};
@@ -9390,37 +10629,72 @@ sub ask_for_embedded_content {
if (ref($args) eq 'HASH') {
$url = $args->{'docs_url'};
$toplevel = $url;
+ if ($args->{'context'} eq 'paste') {
+ ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
+ ($path) =
+ ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
+ $fileloc = &Apache::lonnet::filelocation('',$toplevel);
+ $fileloc =~ s{^/}{};
+ }
}
} elsif ($actionurl eq '/adm/dependencies') {
if ($env{'request.course.id'} ne '') {
- $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
- $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
if (ref($args) eq 'HASH') {
$url = $args->{'docs_url'};
$title = $args->{'docs_title'};
- $toplevel = "/$url";
- ($path) =
- ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
- $fileloc = &Apache::lonnet::filelocation('',$toplevel);
+ $toplevel = $url;
+ unless ($toplevel =~ m{^/}) {
+ $toplevel = "/$url";
+ }
+ ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
+ if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
+ $path = $1;
+ } else {
+ ($path) =
+ ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
+ }
+ if ($toplevel=~/^\/*(uploaded|editupload)/) {
+ $fileloc = $toplevel;
+ $fileloc=~ s/^\s*(\S+)\s*$/$1/;
+ my ($udom,$uname,$fname) =
+ ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
+ $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
+ } else {
+ $fileloc = &Apache::lonnet::filelocation('',$toplevel);
+ }
$fileloc =~ s{^/}{};
($filename) = ($fileloc =~ m{.+/([^/]+)$});
$heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
}
}
- }
- my $now = time();
- foreach my $embed_file (keys(%{$allfiles})) {
- my $absolutepath;
+ } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
+ $udom = $cdom;
+ $uname = $cnum;
+ $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
+ $toplevel = $url;
+ $path = $url;
+ $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
+ $fileloc =~ s{^/}{};
+ }
+ foreach my $file (keys(%{$allfiles})) {
+ my $embed_file;
+ if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
+ $embed_file = $1;
+ } else {
+ $embed_file = $file;
+ }
+ my ($absolutepath,$cleaned_file);
if ($embed_file =~ m{^\w+://}) {
- $newfiles{$embed_file} = 1;
- $mapping{$embed_file} = $embed_file;
+ $cleaned_file = $embed_file;
+ $newfiles{$cleaned_file} = 1;
+ $mapping{$cleaned_file} = $embed_file;
} else {
+ $cleaned_file = &clean_path($embed_file);
if ($embed_file =~ m{^/}) {
$absolutepath = $embed_file;
- $embed_file =~ s{^(/+)}{};
}
- if ($embed_file =~ m{/}) {
- my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
+ if ($cleaned_file =~ m{/}) {
+ my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
$path = &check_for_traversal($path,$url,$toplevel);
my $item = $fname;
if ($path ne '') {
@@ -9437,9 +10711,9 @@ sub ask_for_embedded_content {
} else {
$dependencies{$embed_file} = 1;
if ($absolutepath) {
- $mapping{$embed_file} = $absolutepath;
+ $mapping{$cleaned_file} = $absolutepath;
} else {
- $mapping{$embed_file} = $embed_file;
+ $mapping{$cleaned_file} = $embed_file;
}
}
}
@@ -9447,7 +10721,8 @@ sub ask_for_embedded_content {
my $dirptr = 16384;
foreach my $path (keys(%subdependencies)) {
$currsubfile{$path} = {};
- if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
+ if (($actionurl eq '/adm/portfolio') ||
+ ($actionurl eq '/adm/coursegrp_portfolio')) {
my ($sublistref,$listerror) =
&Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
if (ref($sublistref) eq 'ARRAY') {
@@ -9461,9 +10736,17 @@ sub ask_for_embedded_content {
my @subdir_list = grep(!/^\./,readdir($dir));
map {$currsubfile{$path}{$_} = 1;} @subdir_list;
}
- } elsif ($actionurl eq '/adm/dependencies') {
+ } elsif (($actionurl eq '/adm/dependencies') ||
+ (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
+ ($args->{'context'} eq 'paste')) ||
+ ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
if ($env{'request.course.id'} ne '') {
- my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
+ my $dir;
+ if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
+ $dir = $fileloc;
+ } else {
+ ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
+ }
if ($dir ne '') {
my ($sublistref,$listerror) =
&Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
@@ -9497,6 +10780,12 @@ sub ask_for_embedded_content {
if (ref($currsubfile{$path}) eq 'HASH') {
foreach my $file (keys(%{$currsubfile{$path}})) {
unless ($subdependencies{$path}{$file}) {
+ next if (($rem ne '') &&
+ (($env{"httpref.$rem"."$path/$file"} ne '') ||
+ (ref($navmap) &&
+ (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
+ (($file =~ /^(.*\.s?html?)\.bak$/i) &&
+ ($navmap->getResourceByUrl($rem."$path/$1")))))));
$unused{$path.'/'.$file} = 1;
}
}
@@ -9505,7 +10794,8 @@ sub ask_for_embedded_content {
}
}
my %currfile;
- if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
+ if (($actionurl eq '/adm/portfolio') ||
+ ($actionurl eq '/adm/coursegrp_portfolio')) {
my ($dirlistref,$listerror) =
&Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
if (ref($dirlistref) eq 'ARRAY') {
@@ -9519,7 +10809,10 @@ sub ask_for_embedded_content {
my @dir_list = grep(!/^\./,readdir($dir));
map {$currfile{$_} = 1;} @dir_list;
}
- } elsif ($actionurl eq '/adm/dependencies') {
+ } elsif (($actionurl eq '/adm/dependencies') ||
+ (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
+ ($args->{'context'} eq 'paste')) ||
+ ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
if ($env{'request.course.id'} ne '') {
my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
if ($dir ne '') {
@@ -9553,30 +10846,55 @@ sub ask_for_embedded_content {
unless (($file eq $filename) ||
($file eq $filename.'.bak') ||
($dependencies{$file})) {
+ if ($actionurl eq '/adm/dependencies') {
+ unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
+ next if (($rem ne '') &&
+ (($env{"httpref.$rem".$file} ne '') ||
+ (ref($navmap) &&
+ (($navmap->getResourceByUrl($rem.$file) ne '') ||
+ (($file =~ /^(.*\.s?html?)\.bak$/i) &&
+ ($navmap->getResourceByUrl($rem.$1)))))));
+ }
+ }
$unused{$file} = 1;
}
}
+ if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
+ ($args->{'context'} eq 'paste')) {
+ $counter = scalar(keys(%existing));
+ $numpathchg = scalar(keys(%pathchanges));
+ return ($output,$counter,$numpathchg,\%existing);
+ } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
+ (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
+ $counter = scalar(keys(%existing));
+ $numpathchg = scalar(keys(%pathchanges));
+ return ($output,$counter,$numpathchg,\%existing,\%mapping);
+ }
foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
if ($actionurl eq '/adm/dependencies') {
next if ($embed_file =~ m{^\w+://});
}
$upload_output .= &start_data_table_row().
- ' '.
+ ' '.
''.$embed_file.' ';
unless ($mapping{$embed_file} eq $embed_file) {
- $upload_output .= ''.&mt('changed from: [_1]',$mapping{$embed_file}).' ';
+ $upload_output .= ''.
+ &mt('changed from: [_1]',$mapping{$embed_file}).' ';
}
- $upload_output .= '';
+ $upload_output .= ' ';
if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
- $upload_output.=''.&mt("URL points to other server.").' ';
+ $upload_output.=''.
+ ''.
+ &mt("URL points to web address").' ';
$numremref++;
} elsif ($args->{'error_on_invalid_names'}
&& $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
-
- $upload_output.=''.&mt('Invalid characters').' ';
+ $upload_output.=' '.
+ &mt('Invalid characters').' ';
$numinvalid++;
} else {
- $upload_output .= &embedded_file_element('upload_embedded',$counter,
+ $upload_output .= ''.
+ &embedded_file_element('upload_embedded',$counter,
$embed_file,\%mapping,
$allfiles,$codebase,'upload');
$counter ++;
@@ -9605,8 +10923,9 @@ sub ask_for_embedded_content {
$counter ++;
} else {
$upload_output .= &start_data_table_row().
- ' '.$embed_file.' ';
- ''.&mt('Already exists').' '.
+ ' '.
+ ''.$embed_file.' '.
+ ''.&mt('Already exists').' '.
&Apache::loncommon::end_data_table_row()."\n";
}
}
@@ -9701,7 +11020,7 @@ sub ask_for_embedded_content {
$output = ''.&mt('Referenced files').' : ';
if ($applies > 1) {
$output .=
- &mt('No files need to be uploaded, as one of the following applies to each reference:').'';
+ &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'';
if ($numremref) {
$output .= ''.&mt('reference is to a URL which points to another server').' '."\n";
}
@@ -9744,7 +11063,7 @@ sub ask_for_embedded_content {
$chgcount ++;
}
}
- if ($counter) {
+ if (($counter) || ($numunused)) {
if ($numpathchg) {
$output .= ' '."\n";
@@ -9757,17 +11076,57 @@ sub ask_for_embedded_content {
} elsif ($actionurl eq '/adm/dependencies') {
$output .= ' ';
}
- $output .= ' '."\n".''."\n";
+ $output .= ' '."\n".''."\n";
} elsif ($numpathchg) {
my %pathchange = ();
$output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
$output .= ''.&mt('or').'
';
- }
+ }
}
return ($output,$counter,$numpathchg);
}
+=pod
+
+=item * clean_path($name)
+
+Performs clean-up of directories, subdirectories and filename in an
+embedded object, referenced in an HTML file which is being uploaded
+to a course or portfolio, where
+"Upload embedded images/multimedia files if HTML file" checkbox was
+checked.
+
+Clean-up is similar to replacements in lonnet::clean_filename()
+except each / between sub-directory and next level is preserved.
+
+=cut
+
+sub clean_path {
+ my ($embed_file) = @_;
+ $embed_file =~s{^/+}{};
+ my @contents;
+ if ($embed_file =~ m{/}) {
+ @contents = split(/\//,$embed_file);
+ } else {
+ @contents = ($embed_file);
+ }
+ my $lastidx = scalar(@contents)-1;
+ for (my $i=0; $i<=$lastidx; $i++) {
+ $contents[$i]=~s{\\}{/}g;
+ $contents[$i]=~s/\s+/\_/g;
+ $contents[$i]=~s{[^/\w\.\-]}{}g;
+ if ($i == $lastidx) {
+ $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
+ }
+ }
+ if ($lastidx > 0) {
+ return join('/',@contents);
+ } else {
+ return $contents[0];
+ }
+}
+
sub embedded_file_element {
my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
@@ -9892,28 +11251,31 @@ sub upload_embedded {
# Check if extension is valid
if (($fname =~ /\.(\w+)$/) &&
(&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
- $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).' ';
+ $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
+ .' '.&mt('Rename the file with a different extension and re-upload.').' ';
next;
} elsif (($fname =~ /\.(\w+)$/) &&
(!defined(&Apache::loncommon::fileembstyle($1)))) {
$output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).' ';
next;
} elsif ($fname=~/\.(\d+)\.(\w+)$/) {
- $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).' ';
+ $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).' ';
next;
}
$env{'form.embedded_item_'.$i.'.filename'}=$fname;
+ my $subdir = $path;
+ $subdir =~ s{/+$}{};
if ($context eq 'portfolio') {
my $result;
if ($state eq 'existingfile') {
$result=
&Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
- $dirpath.$env{'form.currentpath'}.$path);
+ $dirpath.$env{'form.currentpath'}.$subdir);
} else {
$result=
&Apache::lonnet::userfileupload('embedded_item_'.$i,'',
$dirpath.
- $env{'form.currentpath'}.$path);
+ $env{'form.currentpath'}.$subdir);
if ($result !~ m|^/uploaded/|) {
$output .= ''
.&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
@@ -9925,10 +11287,11 @@ sub upload_embedded {
$path.$fname.' ').' ';
}
}
- } elsif ($context eq 'coursedoc') {
+ } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
+ my $extendedsubdir = $dirpath.'/'.$subdir;
+ $extendedsubdir =~ s{/+$}{};
my $result =
- &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
- $dirpath.'/'.$path);
+ &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
if ($result !~ m|^/uploaded/|) {
$output .= ''
.&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
@@ -9938,6 +11301,9 @@ sub upload_embedded {
} else {
$output .= &mt('Uploaded [_1]',''.
$path.$fname.' ').' ';
+ if ($context eq 'syllabus') {
+ &Apache::lonnet::make_public_indefinitely($result);
+ }
}
} else {
# Save the file
@@ -10069,7 +11435,7 @@ 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'};
@@ -10078,12 +11444,14 @@ sub modify_html_refs {
} 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');
- unless (@changes > 0) {
+ unless ((@changes > 0) || ($context eq 'syllabus')) {
if (wantarray) {
return ('',0,0);
} else {
@@ -10091,7 +11459,7 @@ sub modify_html_refs {
}
}
if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
- ($context eq 'manage_dependencies')) {
+ ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
if (wantarray) {
return ('',0,0);
@@ -10115,7 +11483,7 @@ sub modify_html_refs {
return;
}
}
- if (open(my $fh,"<$container")) {
+ if (open(my $fh,'<',$container)) {
$content = join('', <$fh>);
close($fh);
} else {
@@ -10147,6 +11515,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});
@@ -10155,10 +11525,11 @@ sub modify_html_refs {
}
}
}
+ my $skiprewrites;
if ($count || $codebasecount) {
my $saveresult;
if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
- ($context eq 'manage_dependencies')) {
+ ($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{/([^/]+)$});
@@ -10171,8 +11542,13 @@ sub modify_html_refs {
''.
$container.' ').'';
}
+ if ($context eq 'syllabus') {
+ unless ($saveresult eq 'ok') {
+ $skiprewrites = 1;
+ }
+ }
} else {
- if (open(my $fh,">$container")) {
+ if (open(my $fh,'>',$container)) {
print $fh $content;
close($fh);
$output = ''.&mt('Updated [quant,_1,reference] in [_2].',
@@ -10186,6 +11562,47 @@ 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);
@@ -10275,11 +11692,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);
}
}
@@ -10288,21 +11705,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);
}
}
@@ -10393,16 +11810,66 @@ sub decompress_form {
}
}
if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
- my @camtasia = ("$topdir/","$topdir/index.html",
+ 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 @diffs = &compare_arrays(\@paths,\@camtasia);
+ 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 = 1;
+ $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;
+ }
+ }
}
}
my $output;
@@ -10414,8 +11881,7 @@ sub decompress_form {
function camtasiaToggle() {
for (var i=0; i '.
''.$lt{'proa'}.''.
- ' '.
+ ' '.
$lt{'yes'}.' '.
' '.
$lt{'no'}.' '.
@@ -10599,10 +12065,22 @@ sub decompress_uploaded_file {
sub process_decompression {
my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
+ unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
+ return ''.&mt('Not extracted.').' '.
+ &mt('Unexpected file path.').'
'."\n";
+ }
+ unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
+ return ''.&mt('Not extracted.').' '.
+ &mt('Unexpected course context.').'
'."\n";
+ }
+ unless ($file eq &Apache::lonnet::clean_filename($file)) {
+ return ''.&mt('Not extracted.').' '.
+ &mt('Filename contained unexpected characters.').'
'."\n";
+ }
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);
@@ -10633,30 +12111,44 @@ sub process_decompression {
}
}
my $numskip = scalar(@to_skip);
- if (($numskip > 0) &&
- ($numskip == $env{'form.archive_itemcount'})) {
+ my $numoverwrite = scalar(@to_overwrite);
+ if (($numskip) && (!$numoverwrite)) {
$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);
- if ($numskip > 0) {
+ if (($numskip) || ($numoverwrite)) {
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");
+ if (&File::Copy::move("$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") {
+ &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
+ }
+ }
+ }
+ foreach my $item (@to_overwrite) {
+ if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
+ if (($item ne '') && ($item !~ /\.\./)) {
+ if (-f "$dir/$item") {
+ unlink("$dir/$item");
+ } elsif (-d "$dir/$item") {
+ &File::Path::remove_tree("$dir/$item",{ safe => 1 });
+ }
+ &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
+ }
}
}
+ if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
+ &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
+ }
}
- system("mv $dir/$tempdir/* $dir");
- rmdir("$dir/$tempdir");
} else {
($decompressed,$display) =
&decompress_uploaded_file($file,$dir);
@@ -10674,8 +12166,7 @@ sub process_decompression {
if (ref($newdirlistref) eq 'ARRAY') {
foreach my $dir_line (@{$newdirlistref}) {
my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
- unless (($item =~ /^\.+$/) || ($item eq $file) ||
- ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
+ unless (($item =~ /^\.+$/) || ($item eq $file)) {
push(@newitems,$item);
if ($dirptr&$testdir) {
$is_dir{$item} = 1;
@@ -10710,6 +12201,7 @@ sub process_decompression {
\%titles,\%children);
}
if ($env{'form.autoextract_camtasia'}) {
+ my $version = $env{'form.autoextract_camtasia'};
my %displayed;
my $total = 1;
$env{'form.archive_directory'} = [];
@@ -10728,12 +12220,15 @@ sub process_decompression {
$env{'form.archive_'.$i} = 'display';
$env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
$displayed{'folder'} = $i;
- } elsif ($item eq "$contents[0]/index.html") {
+ } 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") {
+ 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';
@@ -11060,7 +12555,10 @@ function dependencyCheck(form,count,offs
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'."\n";
+ $result .= ''.&mt('Folder: [_1] added to course',
+ &HTML::Entities::encode($docstitle,'<>&"'))..
+ ' '."\n";
}
}
} else {
@@ -11263,116 +12764,138 @@ sub process_extracted_files {
my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
$docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
$title;
- if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
- mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
- }
- if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
- mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
- }
- 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;
+ if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
+ if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
+ mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
}
- }
- $LONCAPA::map::resources[$newidx]=
- $docstitle.':'.$url.':false:normal:res';
- push(@LONCAPA::map::order, $newidx);
- my ($outtext,$errtext)=
- &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
- $docuname.'/'.$folders{$outer}.
- '.'.$containers{$outer},1);
- unless ($errtext) {
- if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
- $result .= ''.&mt('File: [_1] added to course',$docstitle).' '."\n";
+ if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
+ mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
}
+ if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
+ if (rename("$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]=
+ $docstitle.':'.$url.':false:normal:res';
+ push(@LONCAPA::map::order, $newidx);
+ my ($outtext,$errtext)=
+ &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
+ $docuname.'/'.$folders{$outer}.
+ '.'.$containers{$outer},1,1);
+ unless ($errtext) {
+ if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
+ $result .= ''.&mt('File: [_1] added to course',
+ &HTML::Entities::encode($docstitle,'<>&"')).
+ ' '."\n";
+ }
+ }
+ } else {
+ $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
+ &HTML::Entities::encode($path,'<>&"')).' ';
}
}
}
- } elsif ($env{'form.archive_'.$i} eq 'dependency') {
- 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);
+ }
+ } else {
+ $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
+ &HTML::Entities::encode($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 (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 ($dirorder{$i}->[$j] eq $container) {
+ $itemidx = $j;
}
}
- if ($itemidx ne '') {
- 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;
+ }
+ 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;
+ }
+ }
+ } 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;
- }
+ }
+ }
+ if ($fullpath ne '') {
+ if (-e "$prefix$path") {
+ unless (rename("$prefix$path","$fullpath/$title")) {
+ $warning .= &mt('Failed to rename dependency').' ';
+ }
+ }
+ if (-e "$fullpath/$title") {
+ my $showpath;
+ if ($relpath ne '') {
+ $showpath = "$relpath/$title";
+ } else {
+ $showpath = "/$title";
+ }
+ $result .= ''.&mt('[_1] included as a dependency',
+ &HTML::Entities::encode($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}}).' ';
}
+ } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
+ $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
+ &HTML::Entities::encode($path,'<>&"'),
+ &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
+ ' ';
}
} else {
- $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).' ';
+ $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
+ &HTML::Entities::encode($path)).' ';
}
}
if (keys(%todelete)) {
@@ -11431,7 +12954,7 @@ sub cleanup_empty_dirs {
my $numitems = 0;
foreach my $item (@dircontents) {
if (-d "$path/$item") {
- &recurse_dirs("$path/$item");
+ &cleanup_empty_dirs("$path/$item");
if (-e "$path/$item") {
$numitems ++;
}
@@ -11450,7 +12973,7 @@ sub cleanup_empty_dirs {
=pod
-=item &get_folder_hierarchy()
+=item * &get_folder_hierarchy()
Provides hierarchy of names of folders/sub-folders containing the current
item,
@@ -11478,7 +13001,7 @@ sub get_folder_hierarchy {
my @pcs = split(/,/,$pcslist);
foreach my $pc (@pcs) {
if ($pc == 1) {
- push(@pathitems,&mt('Main Course Documents'));
+ push(@pathitems,&mt('Main Content'));
} else {
my $res = $navmap->getByMapPc($pc);
if (ref($res)) {
@@ -11493,7 +13016,7 @@ sub get_folder_hierarchy {
}
if ($showitem) {
if ($mapres->{ID} eq '0.0') {
- push(@pathitems,&mt('Main Course Documents'));
+ push(@pathitems,&mt('Main Content'));
} else {
my $maptitle = $mapres->compTitle();
$maptitle =~ s/\W+/_/g;
@@ -11560,6 +13083,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);
}
}
@@ -11568,6 +13094,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') {
@@ -11608,6 +13137,9 @@ sub get_turnedin_filepath {
$restitle = time;
}
}
+ if (length($restitle) > 12) {
+ $restitle = substr($restitle,0,12);
+ }
push(@pathitems,$restitle);
$path .= join('/',@pathitems);
}
@@ -11637,12 +13169,15 @@ sub upfile_store {
$env{'form.upfile'}=~s/\n+/\n/gs;
$env{'form.upfile'}=~s/\n+$//gs;
- my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
- '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
+ my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
+ '_enroll_'.$env{'request.course.id'}.'_'.
+ time.'_'.$$);
+ return if ($datatoken eq '');
+
{
my $datafile = $r->dir_config('lonDaemons').
'/tmp/'.$datatoken.'.tmp';
- if ( open(my $fh,">$datafile") ) {
+ if ( open(my $fh,'>',$datafile) ) {
print $fh $env{'form.upfile'};
close($fh);
}
@@ -11652,21 +13187,22 @@ sub upfile_store {
=pod
-=item * &load_tmp_file($r)
+=item * &load_tmp_file($r,$datatoken)
Load uploaded file from tmp, $r should be the HTTP Request object,
-needs $env{'form.datatoken'},
+$datatoken is the name to assign to the temporary file.
sets $env{'form.upfile'} to the contents of the file
=cut
sub load_tmp_file {
- my $r=shift;
+ my ($r,$datatoken) = @_;
+ return if ($datatoken eq '');
my @studentdata=();
{
my $studentfile = $r->dir_config('lonDaemons').
- '/tmp/'.$env{'form.datatoken'}.'.tmp';
- if ( open(my $fh,"<$studentfile") ) {
+ '/tmp/'.$datatoken.'.tmp';
+ if ( open(my $fh,'<',$studentfile) ) {
@studentdata=<$fh>;
close($fh);
}
@@ -11674,6 +13210,14 @@ sub load_tmp_file {
$env{'form.upfile'}=join('',@studentdata);
}
+sub valid_datatoken {
+ my ($datatoken) = @_;
+ if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
+ return $datatoken;
+ }
+ return;
+}
+
=pod
=item * &upfile_record_sep()
@@ -12114,7 +13658,7 @@ sub DrawBarGraph {
@Labels = @$labels;
} else {
for (my $i=0;$i<@{$Values[0]};$i++) {
- push (@Labels,$i+1);
+ push(@Labels,$i+1);
}
}
#
@@ -12545,18 +14089,22 @@ 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),
+defmail (scalar - email address of default recipient),
+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
+
+origmail (scalar - email address of recipient from loncapa.conf,
+i.e., predates configuration by DC via domainprefs.pm
Returns: comma separated list of addresses to which to send e-mail.
@@ -12569,9 +14117,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') {
@@ -12583,14 +14131,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 'helpdeskmail') && ($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 '') {
@@ -12610,8 +14240,21 @@ sub build_recipient_list {
}
}
}
- my $recipientlist = join(',',@recipients);
- return $recipientlist;
+ if ($mailing eq 'helpdeskmail') {
+ 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;
+ }
}
############################################################
@@ -12702,6 +14345,8 @@ jsarray (reference to array of categorie
subcats (reference to hash of arrays containing all subcategories within each
category, -recursive)
+maxd (reference to hash used to hold max depth for all top-level categories).
+
Returns: nothing
Side effects: populates trails and allitems hash references.
@@ -12709,7 +14354,7 @@ Side effects: populates trails and allit
=cut
sub extract_categories {
- my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
+ my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
if (ref($categories) eq 'HASH') {
&gather_categories($categories,$cats,$idx,$jsarray);
if (ref($cats->[0]) eq 'ARRAY') {
@@ -12735,12 +14380,15 @@ sub extract_categories {
if (ref($subcats) eq 'HASH') {
push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
}
- &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
+ &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
}
} else {
if (ref($subcats) eq 'HASH') {
$subcats->{$item} = [];
}
+ if (ref($maxd) eq 'HASH') {
+ $maxd->{$name} = 1;
+ }
}
}
}
@@ -12750,7 +14398,7 @@ sub extract_categories {
=pod
-=item *&recurse_categories()
+=item * &recurse_categories()
Recursively used to generate breadcrumb trails for course categories.
@@ -12778,7 +14426,7 @@ Side effects: populates trails and allit
=cut
sub recurse_categories {
- my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
+ my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
my $shallower = $depth - 1;
if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
@@ -12805,23 +14453,28 @@ sub recurse_categories {
}
}
&recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
- $subcats);
+ $subcats,$maxd);
pop(@{$parents});
}
} else {
my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
- my $trailstr = join(' -> ',(@{$parents},$category));
+ my $trailstr = join(' » ',(@{$parents},$category));
if ($allitems->{$item} eq '') {
push(@{$trails},$trailstr);
$allitems->{$item} = scalar(@{$trails})-1;
}
+ if (ref($maxd) eq 'HASH') {
+ if ($depth > $maxd->{$parents->[0]}) {
+ $maxd->{$parents->[0]} = $depth;
+ }
+ }
}
return;
}
=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.
@@ -12835,16 +14488,19 @@ 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);
- &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
+ my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
+ &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
$maxdepth = scalar(@cats);
if (@cats > 0) {
my $itemcount = 0;
@@ -12876,11 +14532,11 @@ sub assign_categories_table {
}
$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 ++;
@@ -12898,7 +14554,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.
@@ -12919,12 +14575,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});
@@ -12932,7 +14591,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;
@@ -12947,12 +14606,12 @@ sub assign_category_rows {
}
$text .= ''.
' '.$name.' '.
+ $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 .= ' ';
@@ -12964,6 +14623,12 @@ sub assign_category_rows {
return $text;
}
+=pod
+
+=back
+
+=cut
+
############################################################
############################################################
@@ -12980,7 +14645,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";
@@ -12989,7 +14654,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";
@@ -13020,7 +14685,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";
@@ -13067,7 +14733,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 '') {
@@ -13098,7 +14768,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;
}
@@ -13124,6 +14794,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').' ');
+ }
+}
+
############################################################
############################################################
@@ -13152,37 +14842,95 @@ sub check_clone {
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))) {
+ my %roleshash =
+ &Apache::lonnet::get_my_roles($args->{'ccuname'},
+ $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'});
}
}
}
@@ -13191,7 +14939,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') {
@@ -13287,8 +15036,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'};
+ }
}
#
@@ -13316,6 +15070,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'} = '';
@@ -13331,7 +15088,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/,$//;
@@ -13340,6 +15097,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'}='';
@@ -13354,7 +15116,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/,$//;
@@ -13389,28 +15151,29 @@ 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'}) {
$args->{'endaccess'} = 0;
@@ -13442,6 +15205,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'}.'/';
@@ -13464,6 +15230,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';
}
@@ -13532,6 +15317,60 @@ sub construct_course {
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;
+}
+
############################################################
############################################################
@@ -13559,11 +15398,12 @@ sub group_term {
}
sub course_types {
- my @types = ('official','unofficial','community');
+ my @types = ('official','unofficial','community','textbook');
my %typename = (
official => 'Official course',
unofficial => 'Unofficial course',
community => 'Community',
+ textbook => 'Textbook course',
);
return (\@types,\%typename);
}
@@ -13624,7 +15464,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 {
@@ -13682,6 +15522,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'}
@@ -13695,8 +15546,8 @@ sub init_user_environment {
}
# ------------------------------------ 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
@@ -13727,6 +15578,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" => '',
@@ -13746,23 +15600,51 @@ 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') {
+ $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'};
+ }
+ }
}
$env{'user.environment'} = "$lonids/$cookie.id";
@@ -13849,42 +15731,1226 @@ 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} = '';
}
- } elsif ($item eq 'course') {
- if ($name eq 'crstype') {
- $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
+ }
+ 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);
}
+ } else {
+ $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
}
}
- ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
- ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
+
+ # 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 %lt = &Apache::lonlocal::texthash(
+ 'cac' => "$crstype Activity",
+ 'ccr' => "$crstype Created",
+ 'cde' => "$crstype Title",
+ 'cdo' => "$crstype Domain",
+ 'ins' => 'Institutional Code',
+ 'inc' => 'Institutional Categorization',
+ 'cow' => "$crstype Owner/Co-owner",
+ 'cop' => "$crstype Personnel Includes",
+ 'cog' => 'Type',
+ );
+
+ if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
+ my $typeval = 'Course';
+ if ($crstype eq 'Community') {
+ $typeval = 'Community';
+ }
+ $typeselectform = ' ';
+ } else {
+ $typeselectform = '".&mt($posstype)."\n";
+ }
+ $typeselectform.=" ";
+ }
+
+ my ($cloneableonlyform,$cloneabletitle);
+ if (exists($filter->{'cloneableonly'})) {
+ my $cloneableon = '';
+ my $cloneableoff = ' checked="checked"';
+ if ($filter->{'cloneableonly'}) {
+ $cloneableon = $cloneableoff;
+ $cloneableoff = '';
+ }
+ $cloneableonlyform = ' '.&mt('Required').' '.(' 'x3).' '.&mt('No restriction').' ';
+ 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 <
+//
+
+
+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) {
+ my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
+ &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
+ 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 $ua = LWP::UserAgent->new;
+ $ua->timeout(10);
+ my %info = (
+ secret => $privkey,
+ response => $env{'form.g-recaptcha-response'},
+ remoteip => $ENV{'REMOTE_ADDR'},
+ );
+ my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
+ 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.
+sub critical_redirect {
+ my ($interval) = @_;
+ if ((time-$env{'user.criticalcheck.time'})>$interval) {
+ 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__;