--- loncom/interface/loncommon.pm 2006/09/22 19:59:30 1.459 +++ loncom/interface/loncommon.pm 2007/09/11 20:40:23 1.583 @@ -1,7 +1,7 @@ # The LearningOnline Network with CAPA # a pile of common routines # -# $Id: loncommon.pm,v 1.459 2006/09/22 19:59:30 albertel Exp $ +# $Id: loncommon.pm,v 1.583 2007/09/11 20:40:23 albertel Exp $ # # Copyright Michigan State University Board of Trustees # @@ -59,16 +59,21 @@ use Apache::lonnet; use GDBM_File; use POSIX qw(strftime mktime); use Apache::lonmenu(); +use Apache::lonenc(); use Apache::lonlocal; use HTML::Entities; use Apache::lonhtmlcommon(); use Apache::loncoursedata(); use Apache::lontexconvert(); use Apache::lonclonecourse(); -use LONCAPA; +use LONCAPA qw(:DEFAULT :match); + +# ---------------------------------------------- Designs +use vars qw(%defaultdesign); my $readit; + ## ## Global Variables ## @@ -81,10 +86,6 @@ my %scprtag; my %fe; my %fd; my %fm; my %category_extensions; -# ---------------------------------------------- Designs - -my %designhash; - # ---------------------------------------------- Thesaurus variables # # %Keywords: @@ -150,30 +151,18 @@ BEGIN { } } -# -------------------------------------------------------------- domain designs - - my $filename; +# -------------------------------------------------------------- default domain designs my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors'; - opendir(DIR,$designdir); - while ($filename=readdir(DIR)) { - if ($filename!~/\.tab$/) { next; } - my ($domain)=($filename=~/^(\w+)\./); - { - my $designfile = $designdir.'/'.$filename; - if ( open (my $fh,"<$designfile") ) { - while (my $line = <$fh>) { - next if ($line =~ /^\#/); - chomp($line); - my ($key,$val)=(split(/\=/,$line)); - if ($val) { $designhash{$domain.'.'.$key}=$val; } - } - close($fh); - } - } - + my $designfile = $designdir.'/default.tab'; + if ( open (my $fh,"<$designfile") ) { + while (my $line = <$fh>) { + next if ($line =~ /^\#/); + chomp($line); + my ($key,$val)=(split(/\=/,$line)); + if ($val) { $defaultdesign{$key}=$val; } + } + close($fh); } - closedir(DIR); - # ------------------------------------------------------------- file categories { @@ -345,10 +334,12 @@ sub studentbrowser_javascript { return (<<'ENDSTDBRW'); + + function getFormIdByName(formname) { + for (var i=0;i".&mt('Select [_1]',$selecttype).""; + return "".&mt('Select Course').""; } sub check_uncheck_jscript { @@ -461,7 +526,8 @@ function uncheckAll(field) { if (field.length > 0) { for (i = 0; i < field.length; i++) { field[i].checked = false ; - } } else { + } + } else { field.checked = false ; } } @@ -645,8 +711,7 @@ sub help_open_topic { my ($topic, $text, $stayOnPage, $width, $height) = @_; $text = "" if (not defined $text); $stayOnPage = 0 if (not defined $stayOnPage); - if ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ) { + if ($env{'browser.interface'} eq 'textual') { $stayOnPage=1; } $width = 350 if (not defined $width); @@ -656,24 +721,20 @@ sub help_open_topic { my $template = ""; my $link; - + $topic=~s/\W/\_/g; - if (!$stayOnPage) - { + if (!$stayOnPage) { $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; - } - else - { + } else { $link = "/adm/help/${filename}.hlp"; } # Add the text - if ($text ne "") - { + if ($text ne "") { $template .= - "". - "
$text"; + "". + "'; foreach my $key (sort(keys(%lasthash))) { - my $value; - if ($key =~ /timestamp/) { - $value=scalar(localtime($returnhash{$version.':'.$key})); - } else { - $value=$returnhash{$version.':'.$key}; - } - $prevattempts.=''; + my $value = &format_previous_attempt_value($key, + $returnhash{$version.':'.$key}); + $prevattempts.=''; } } } $prevattempts.=''; foreach my $key (sort(keys(%lasthash))) { - my $value; - if ($key =~ /timestamp/) { - $value=scalar(localtime($lasthash{$key})); - } else { - $value=$lasthash{$key}; - } - $value=&unescape($value); + my $value = &format_previous_attempt_value($key,$lasthash{$key}); if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)} $prevattempts.=''; } @@ -2491,6 +2686,19 @@ sub get_previous_attempt { } } +sub format_previous_attempt_value { + my ($key,$value) = @_; + if ($key =~ /timestamp/) { + $value = &Apache::lonlocal::locallocaltime($value); + } elsif (ref($value) eq 'ARRAY') { + $value = '('.join(', ', @{ $value }).')'; + } else { + $value = &unescape($value); + } + return $value; +} + + sub relative_to_absolute { my ($url,$output)=@_; my $parser=HTML::TokeParser->new(\$output); @@ -2577,7 +2785,8 @@ sub get_student_answers { } $moreenv{'grade_target'}='answer'; %moreenv=(%form,%moreenv); - my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv); + $feedurl = &Apache::lonnet::clutter($feedurl); + my $userview=&Apache::lonnet::ssi($feedurl,%moreenv); return $userview; } @@ -2596,7 +2805,7 @@ sub submlink { my ($text,$uname,$udom,$symb,$target)=@_; if (!($uname && $udom)) { (my $cursymb, my $courseid,$udom,$uname)= - &Apache::lonxml::whichuser($symb); + &Apache::lonnet::whichuser($symb); if (!$symb) { $symb=$cursymb; } } if (!$symb) { $symb=&Apache::lonnet::symbread(); } @@ -2642,7 +2851,7 @@ sub pprmlink { my ($text,$uname,$udom,$symb,$target)=@_; if (!($uname && $udom)) { (my $cursymb, my $courseid,$udom,$uname)= - &Apache::lonxml::whichuser($symb); + &Apache::lonnet::whichuser($symb); if (!$symb) { $symb=$cursymb; } } if (!$symb) { $symb=&Apache::lonnet::symbread(); } @@ -2691,31 +2900,376 @@ sub maketime { ######################################### sub findallcourses { - my ($roles) = @_; + my ($roles,$uname,$udom) = @_; my %roles; if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; } my %courses; my $now=time; - foreach my $key (keys(%env)) { - if ( $key=~m{^user\.role\.(\w+)\./(\w+)/(\w+)} ) { - my ($role,$domain,$id) = ($1,$2,$3); - next if ($role eq 'ca' || $role eq 'aa'); - next if (%roles && !exists($roles{$role})); - my ($starttime,$endtime)=split(/\./,$env{$key}); - my $active=1; - if ($starttime) { - if ($now<$starttime) { $active=0; } + if (!defined($uname)) { + $uname = $env{'user.name'}; + } + if (!defined($udom)) { + $udom = $env{'user.domain'}; + } + if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) { + my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname); + if (!%roles) { + %roles = ( + cc => 1, + in => 1, + ep => 1, + ta => 1, + cr => 1, + st => 1, + ); + } + foreach my $entry (keys(%roleshash)) { + my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry}); + if ($trole =~ /^cr/) { + next if (!exists($roles{$trole}) && !exists($roles{'cr'})); + } else { + next if (!exists($roles{$trole})); } - if ($endtime) { - if ($now>$endtime) { $active=0; } + if ($tend) { + next if ($tend < $now); + } + if ($tstart) { + next if ($tstart > $now); + } + my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec); + (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry); + if ($secpart eq '') { + ($cnum,$role) = split(/_/,$cnumpart); + $sec = 'none'; + $realsec = ''; + } else { + $cnum = $cnumpart; + ($sec,$role) = split(/_/,$secpart); + $realsec = $sec; + } + $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec; + } + } else { + foreach my $key (keys(%env)) { + if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} || + $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) { + my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4); + next if ($role eq 'ca' || $role eq 'aa'); + next if (%roles && !exists($roles{$role})); + my ($starttime,$endtime)=split(/\./,$env{$key}); + my $active=1; + if ($starttime) { + if ($now<$starttime) { $active=0; } + } + if ($endtime) { + if ($now>$endtime) { $active=0; } + } + if ($active) { + if ($sec eq '') { + $sec = 'none'; + } + $courses{$cdom.'_'.$cnum}{$sec} = + $role.'/'.$cdom.'/'.$cnum.'/'.$sec; + } } - if ($active) { $courses{$domain.'_'.$id}=1; } } } - return keys(%courses); + return %courses; } ############################################### + +sub blockcheck { + my ($setters,$activity,$uname,$udom) = @_; + + if (!defined($udom)) { + $udom = $env{'user.domain'}; + } + if (!defined($uname)) { + $uname = $env{'user.name'}; + } + + # If uname and udom are for a course, check for blocks in the course. + + if (&Apache::lonnet::is_course($udom,$uname)) { + my %records = &Apache::lonnet::dump('comm_block',$udom,$uname); + my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname); + return ($startblock,$endblock); + } + + my $startblock = 0; + my $endblock = 0; + my %live_courses = &findallcourses(undef,$uname,$udom); + + # If uname is for a user, and activity is course-specific, i.e., + # boards, chat or groups, check for blocking in current course only. + + if (($activity eq 'boards' || $activity eq 'chat' || + $activity eq 'groups') && ($env{'request.course.id'})) { + foreach my $key (keys(%live_courses)) { + if ($key ne $env{'request.course.id'}) { + delete($live_courses{$key}); + } + } + } + + my $otheruser = 0; + my %own_courses; + if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) { + # Resource belongs to user other than current user. + $otheruser = 1; + # Gather courses for current user + %own_courses = + &findallcourses(undef,$env{'user.name'},$env{'user.domain'}); + } + + # Gather active course roles - course coordinator, instructor, + # exam proctor, ta, student, or custom role. + + foreach my $course (keys(%live_courses)) { + my ($cdom,$cnum); + if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) { + $cdom = $env{'course.'.$course.'.domain'}; + $cnum = $env{'course.'.$course.'.num'}; + } else { + ($cdom,$cnum) = split(/_/,$course); + } + my $no_ownblock = 0; + my $no_userblock = 0; + if ($otheruser && $activity ne 'com') { + # Check if current user has 'evb' priv for this + if (defined($own_courses{$course})) { + foreach my $sec (keys(%{$own_courses{$course}})) { + my $checkrole = 'cm./'.$cdom.'/'.$cnum; + if ($sec ne 'none') { + $checkrole .= '/'.$sec; + } + if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) { + $no_ownblock = 1; + last; + } + } + } + # if they have 'evb' priv and are currently not playing student + next if (($no_ownblock) && + ($env{'request.role'} !~ m{^st\./$cdom/$cnum})); + } + foreach my $sec (keys(%{$live_courses{$course}})) { + my $checkrole = 'cm./'.$cdom.'/'.$cnum; + if ($sec ne 'none') { + $checkrole .= '/'.$sec; + } + if ($otheruser) { + # Resource belongs to user other than current user. + # Assemble privs for that user, and check for 'evb' priv. + my ($trole,$tdom,$tnum,$tsec); + my $entry = $live_courses{$course}{$sec}; + if ($entry =~ /^cr/) { + ($trole,$tdom,$tnum,$tsec) = + ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|); + } else { + ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry); + } + my ($spec,$area,$trest,%allroles,%userroles); + $area = '/'.$tdom.'/'.$tnum; + $trest = $tnum; + if ($tsec ne '') { + $area .= '/'.$tsec; + $trest .= '/'.$tsec; + } + $spec = $trole.'.'.$area; + if ($trole =~ /^cr/) { + &Apache::lonnet::custom_roleprivs(\%allroles,$trole, + $tdom,$spec,$trest,$area); + } else { + &Apache::lonnet::standard_roleprivs(\%allroles,$trole, + $tdom,$spec,$trest,$area); + } + my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles); + if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) { + if ($1) { + $no_userblock = 1; + last; + } + } + } else { + # Resource belongs to current user + # Check for 'evb' priv via lonnet::allowed(). + if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) { + $no_ownblock = 1; + last; + } + } + } + # if they have the evb priv and are currently not playing student + next if (($no_ownblock) && + ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E})); + next if ($no_userblock); + + # Retrieve blocking times and identity of blocker for course + # of specified user, unless user has 'evb' privilege. + + my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum); + if (($start != 0) && + (($startblock == 0) || ($startblock > $start))) { + $startblock = $start; + } + if (($end != 0) && + (($endblock == 0) || ($endblock < $end))) { + $endblock = $end; + } + } + return ($startblock,$endblock); +} + +sub get_blocks { + my ($setters,$activity,$cdom,$cnum) = @_; + my $startblock = 0; + my $endblock = 0; + my $course = $cdom.'_'.$cnum; + $setters->{$course} = {}; + $setters->{$course}{'staff'} = []; + $setters->{$course}{'times'} = []; + my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum); + foreach my $record (keys(%records)) { + my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/); + if ($start <= time && $end >= time) { + my ($staff_name,$staff_dom,$title,$blocks) = + &parse_block_record($records{$record}); + if ($blocks->{$activity} eq 'on') { + push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]); + push(@{$$setters{$course}{'times'}}, [$start,$end]); + if ( ($startblock == 0) || ($startblock > $start) ) { + $startblock = $start; + } + if ( ($endblock == 0) || ($endblock < $end) ) { + $endblock = $end; + } + } + } + } + return ($startblock,$endblock); +} + +sub parse_block_record { + my ($record) = @_; + my ($setuname,$setudom,$title,$blocks); + if (ref($record) eq 'HASH') { + ($setuname,$setudom) = split(/:/,$record->{'setter'}); + $title = &unescape($record->{'event'}); + $blocks = $record->{'blocks'}; + } else { + my @data = split(/:/,$record,3); + if (scalar(@data) eq 2) { + $title = $data[1]; + ($setuname,$setudom) = split(/@/,$data[0]); + } else { + ($setuname,$setudom,$title) = @data; + } + $blocks = { 'com' => 'on' }; + } + return ($setuname,$setudom,$title,$blocks); +} + +sub build_block_table { + my ($startblock,$endblock,$setters) = @_; + my %lt = &Apache::lonlocal::texthash( + 'cacb' => 'Currently active communication blocks', + 'cour' => 'Course', + 'dura' => 'Duration', + 'blse' => 'Block set by' + ); + my $output; + $output = '
'.$lt{'cacb'}.':
'; + $output .= &start_data_table(); + $output .= ' + + + + + +'; + foreach my $course (keys(%{$setters})) { + my %courseinfo=&Apache::lonnet::coursedescription($course); + for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) { + my ($uname,$udom) = @{$$setters{$course}{staff}[$i]}; + my $fullname = &plainname($uname,$udom); + if (defined($env{'user.name'}) && defined($env{'user.domain'}) + && $env{'user.name'} ne 'public' + && $env{'user.domain'} ne 'public') { + $fullname = &aboutmewrapper($fullname,$uname,$udom); + } + my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]}; + $openblock = &Apache::lonlocal::locallocaltime($openblock); + $closeblock= &Apache::lonlocal::locallocaltime($closeblock); + $output .= &Apache::loncommon::start_data_table_row(). + ''. + ''. + ''. + &Apache::loncommon::end_data_table_row(); + } + } + $output .= &end_data_table(); +} + +sub blocking_status { + my ($activity,$uname,$udom) = @_; + my %setters; + my ($blocked,$output,$ownitem,$is_course); + my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom); + if ($startblock && $endblock) { + $blocked = 1; + if (wantarray) { + my $category; + if ($activity eq 'boards') { + $category = 'Discussion posts in this course'; + } elsif ($activity eq 'blogs') { + $category = 'Blogs'; + } elsif ($activity eq 'port') { + if (defined($uname) && defined($udom)) { + if ($uname eq $env{'user.name'} && + $udom eq $env{'user.domain'}) { + $ownitem = 1; + } + } + $is_course = &Apache::lonnet::is_course($udom,$uname); + if ($ownitem) { + $category = 'Your portfolio files'; + } elsif ($is_course) { + my $coursedesc; + foreach my $course (keys(%setters)) { + my %courseinfo = + &Apache::lonnet::coursedescription($course); + $coursedesc = $courseinfo{'description'}; + } + $category = "Group files in the course '$coursedesc'"; + } else { + $category = 'Portfolio files belonging to '; + if ($env{'user.name'} eq 'public' && + $env{'user.domain'} eq 'public') { + $category .= &plainname($uname,$udom); + } else { + $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom); + } + } + } elsif ($activity eq 'groups') { + $category = 'Groups in this course'; + } + my $showstart = &Apache::lonlocal::locallocaltime($startblock); + my $showend = &Apache::lonlocal::locallocaltime($endblock); + $output = '
'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'
'; + if (!($activity eq 'port' && !($ownitem) && !($is_course))) { + $output .= &build_block_table($startblock,$endblock,\%setters); + } + } + } + if (wantarray) { + return ($blocked,$output); + } else { + return $blocked; + } +} + ############################################### =pod @@ -2735,7 +3289,7 @@ Returns: Determines which domain should ############################################### sub determinedomain { my $domain=shift; - if (! $domain) { + if (! $domain) { # Determine domain if we have not been given one $domain = $Apache::lonnet::perlvar{'lonDefDomain'}; if ($env{'user.domain'}) { $domain=$env{'user.domain'}; } @@ -2746,6 +3300,60 @@ sub determinedomain { return $domain; } ############################################### + +sub devalidate_domconfig_cache { + my ($udom)=@_; + &Apache::lonnet::devalidate_cache_new('domainconfig',$udom); +} + +# ---------------------- Get domain configuration for a domain +sub get_domainconf { + my ($udom) = @_; + my $cachetime=1800; + my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom); + if (defined($cached)) { return %{$result}; } + + my %domconfig = &Apache::lonnet::get_dom('configuration', + ['login','rolecolors'],$udom); + my %designhash; + if (keys(%domconfig) > 0) { + if (ref($domconfig{'login'}) eq 'HASH') { + foreach my $key (keys(%{$domconfig{'login'}})) { + $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key}; + } + } + if (ref($domconfig{'rolecolors'}) eq 'HASH') { + foreach my $role (keys(%{$domconfig{'rolecolors'}})) { + if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') { + foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) { + $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item}; + } + } + } + } + } else { + my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors'; + my $designfile = $designdir.'/'.$udom.'.tab'; + if (-e $designfile) { + if ( open (my $fh,"<$designfile") ) { + while (my $line = <$fh>) { + next if ($line =~ /^\#/); + chomp($line); + my ($key,$val)=(split(/\=/,$line)); + if ($val) { $designhash{$udom.'.'.$key}=$val; } + } + close($fh); + } + } + if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') { + $designhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif"; + } + } + &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash, + $cachetime); + return %designhash; +} + =pod =item * &domainlogo() @@ -2759,13 +3367,21 @@ If the domain logo does not exist, a des ############################################### sub domainlogo { - my $domain = &determinedomain(shift); - # See if there is a logo - if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') { - my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif"); - return ''.$domain.''; - } elsif(exists($Apache::lonnet::domaindescription{$domain})) { - return $Apache::lonnet::domaindescription{$domain}; + my $domain = &determinedomain(shift); + my %designhash = &get_domainconf($domain); + # See if there is a logo + if ($designhash{$domain.'.login.domlogo'} ne '') { + my $imgsrc = $designhash{$domain.'.login.domlogo'}; + if ($imgsrc =~ m{^/(adm|res)/}) { + if ($imgsrc =~ m{^/res/}) { + my $local_name = &Apache::lonnet::filelocation('',$imgsrc); + &Apache::lonnet::repcopy($local_name); + } + $imgsrc = &lonhttpdurl($imgsrc); + } + return ''.$domain.''; + } elsif (defined(&Apache::lonnet::domain($domain,'description'))) { + return &Apache::lonnet::domain($domain,'description'); } else { return ''; } @@ -2801,11 +3417,24 @@ sub designparm { return $env{'environment.color.'.$which}; } $domain=&determinedomain($domain); - if (exists($designhash{$domain.'.'.$which})) { - return $designhash{$domain.'.'.$which}; + my %domdesign = &get_domainconf($domain); + my $output; + if ($domdesign{$domain.'.'.$which} ne '') { + $output = $domdesign{$domain.'.'.$which}; } else { - return $designhash{'default.'.$which}; + $output = $defaultdesign{$which}; + } + if (($which =~ /^(student|coordinator|author|admin)\.img$/) || + ($which =~ /login\.(img|logo|domlogo)/)) { + if ($output =~ m{^/(adm|res)/}) { + if ($output =~ m{^/res/}) { + my $local_name = &Apache::lonnet::filelocation('',$output); + &Apache::lonnet::repcopy($local_name); + } + $output = &lonhttpdurl($output); + } } + return $output; } ############################################### @@ -2815,7 +3444,7 @@ sub designparm { =back -=head1 HTTP Helpers +=head1 HTML Helpers =over 4 @@ -2854,6 +3483,12 @@ Inputs: =item * $no_inline_link, if true and in remote mode, don't show the 'Switch To Inline Menu' link +=item * $args, optional argument valid values are + no_auto_mt_title -> prevents &mt()ing the title arg + inherit_jsmath -> when creating popup window in a page, + should it have jsmath forced on by the + current page + =back Returns: A uniform header for LON-CAPA web pages. @@ -2865,9 +3500,9 @@ other decorations will be returned. sub bodytag { my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle, - $notopbar,$bgcolor,$notitle,$no_inline_link)=@_; + $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_; - $title=&mt($title); + if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } $function = &get_users_function() if (!$function); my $img = &designparm($function.'.img',$domain); @@ -2885,8 +3520,8 @@ sub bodytag { # role and realm my ($role,$realm) = split(/\./,$env{'request.role'},2); if ($role eq 'ca') { - my ($rdom,$rname) = ($realm =~ m-^/(\w+)/(\w+)$-); - $realm = &plainname($rname,$rdom).':'.$rdom; + my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$}); + $realm = &plainname($rname,$rdom); } # realm if ($env{'request.course.id'}) { @@ -2901,19 +3536,14 @@ sub bodytag { if (!$realm) { $realm=' '; } # Set messages my $messages=&domainlogo($domain); -# Port for miniserver - my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'}; - if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; } my $extra_body_attr = &make_attr_string($forcereg,\%design); # construct main body tag my $bodytag = "". - &Apache::lontexconvert::init_math_support(); + &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'}); - if ($bodyonly - || ($env{'request.state'} eq 'construct' - && $env{'environment.remote'} ne 'off' )) { + if ($bodyonly) { return $bodytag; } elsif ($env{'browser.interface'} eq 'textual') { # Accessibility @@ -3021,8 +3651,11 @@ ENDROLE # Top frame rendering, Remote is up # - my $upperleft=''.$function.''; + my $imgsrc = $img; + if ($img =~ /^\/adm/) { + $imgsrc = &lonhttpdurl($img); + } + my $upperleft=''.$function.''; # Explicit link to get inline menu my $menu= ($no_inline_link?'' @@ -3105,20 +3738,12 @@ sub make_attr_string { =pod -=back - -=head1 HTML Helpers - -=over 4 - =item * &endbodytag() Returns a uniform footer for LON-CAPA web pages. Inputs: none -=back - =cut sub endbodytag { @@ -3135,8 +3760,6 @@ sub endbodytag { =pod -=over 4 - =item * &standard_css() Returns a style sheet @@ -3147,8 +3770,6 @@ Inputs: (all optional) function -> force usage of a specific rolish color scheme bgcolor -> override the default page bgcolor -=back - =cut sub standard_css { @@ -3170,8 +3791,8 @@ sub standard_css { my $mono = 'monospace'; my $data_table_head = $tabbg; my $data_table_light = '#EEEEEE'; - my $data_table_dark = '#DDD'; - my $data_table_darker = '#CCC'; + my $data_table_dark = '#DDDDDD'; + my $data_table_darker = '#CCCCCC'; my $data_table_highlight = '#FFFF00'; my $mail_new = '#FFBB77'; my $mail_new_hover = '#DD9955'; @@ -3182,16 +3803,26 @@ sub standard_css { my $mail_other = '#99BBBB'; my $mail_other_hover = '#669999'; my $table_header = '#DDDDDD'; + my $feedback_link_bg = '#BBBBBB'; my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px' : '0px 3px 0px 4px'; + return < force usage of a specific rolish color scheme bgcolor -> override the default page bgcolor - -=back + no_auto_mt_title + -> prevent &mt()ing the title arg =cut @@ -3744,9 +4693,11 @@ sub headtag { my $result = ''. - &font_settings(). - &Apache::lonhtmlcommon::htmlareaheaders(); + &font_settings(); + if (!$args->{'frameset'}) { + $result .= &Apache::lonhtmlcommon::htmlareaheaders(); + } if ($args->{'force_register'}) { $result .= &Apache::lonmenu::registerurl(1); } @@ -3770,8 +4721,8 @@ ADDMETA if (!defined($title)) { $title = 'The LearningOnline Network with CAPA'; } - - $result .= ' LON-CAPA '.&mt($title).'' + if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } + $result .= ' LON-CAPA '.$title.'' .'' .$head_extra; return $result; @@ -3779,16 +4730,12 @@ ADDMETA =pod -=over 4 - =item * &font_settings() Returns neccessary to set the proper encoding Inputs: none -=back - =cut sub font_settings { @@ -3805,16 +4752,12 @@ sub font_settings { =pod -=over 4 - =item * &xml_begin() Returns the needed doctype and Inputs: none -=back - =cut sub xml_begin { @@ -3839,16 +4782,12 @@ sub xml_begin { =pod -=over 4 - =item * &endheadtag() Returns a uniform for LON-CAPA web pages. Inputs: none -=back - =cut sub endheadtag { @@ -3857,8 +4796,6 @@ sub endheadtag { =pod -=over 4 - =item * &head() Returns a uniform complete .. section for LON-CAPA web pages. @@ -3866,8 +4803,6 @@ Returns a uniform complete .. -=back - =cut sub head { @@ -3877,8 +4812,6 @@ sub head { =pod -=over 4 - =item * &start_page() Returns a complete .. section for LON-CAPA web pages. @@ -3915,7 +4848,11 @@ Inputs: $title - optional title for the no_inline_link -> if true and in remote mode, don't show the 'Switch To Inline Menu' link -=back + no_auto_mt_title -> prevent &mt()ing the title arg + + inherit_jsmath -> when creating popup window in a page, + should it have jsmath forced on by the + current page =cut @@ -3924,7 +4861,8 @@ sub start_page { #&Apache::lonnet::logthis("start_page ".join(':',caller(0))); my %head_args; foreach my $arg ('redirect','force_register','domain','function', - 'bgcolor','frameset','no_nav_bar','only_body') { + 'bgcolor','frameset','no_nav_bar','only_body', + 'no_auto_mt_title') { if (defined($args->{$arg})) { $head_args{$arg} = $args->{$arg}; } @@ -3950,7 +4888,8 @@ sub start_page { $args->{'only_body'}, $args->{'domain'}, $args->{'force_register'}, $args->{'body_title'}, $args->{'no_nav_bar'}, $args->{'bgcolor'}, - $args->{'no_title'}, $args->{'no_inline_link'}); + $args->{'no_title'}, $args->{'no_inline_link'}, + $args); } } @@ -3966,8 +4905,6 @@ sub start_page { =pod -=over 4 - =item * &head() Returns a complete section for LON-CAPA web pages. @@ -3979,6 +4916,11 @@ Inputs: $args - additional optio a html attribute frameset -> if true will start with a rather than + dicsussion -> if true will get discussion from + lonxml::xmlend + (you can pass the target and parser arguments + through optional 'target' and 'parser' args + to this routine) =cut @@ -4090,6 +5032,13 @@ sub simple_error_page { $css_class = (join(' ',$css_class,$add_class)); return ''."\n";; } + + sub continue_data_table_row { + my ($add_class) = @_; + my $css_class = ($row_count % 2)?'':'LC_even_row'; + $css_class = (join(' ',$css_class,$add_class)); + return ''."\n";; + } sub end_data_table_row { return ''."\n";; @@ -4113,10 +5062,61 @@ sub simple_error_page { } } +=pod + +=item * &inhibit_menu_check($arg) + +Checks for a inhibitmenu state and generates output to preserve it + +Inputs: $arg - can be any of + - undef - in which case the return value is a string + to add into arguments list of a uri + - 'input' - in which case the return value is a HTML + field of type hidden to + preserve the value + - a url - in which case the return value is the url with + the neccesary cgi args added to preserve the + inhibitmenu state + - a ref to a url - no return value, but the string is + updated to include the neccessary cgi + args to preserve the inhibitmenu state + +=cut + +sub inhibit_menu_check { + my ($arg) = @_; + &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']); + if ($arg eq 'input') { + if ($env{'form.inhibitmenu'}) { + return ''; + } else { + return + } + } + if ($env{'form.inhibitmenu'}) { + if (ref($arg)) { + $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'}; + } elsif ($arg eq '') { + $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'}; + } else { + $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'}; + } + } + if (!ref($arg)) { + return $arg; + } +} + ############################################### =pod +=back + +=head1 User Information Routines + +=over 4 + =item * &get_users_function() Used by &bodytag to determine the current users primary role. @@ -4144,7 +5144,7 @@ sub get_users_function { =pod -=item * &check_user_status +=item * &check_user_status() Determines current status of supplied role for a specific user. Roles can be active, previous or future. @@ -4430,7 +5430,7 @@ sub get_course_users { $usec = 'none'; } if ($uname ne '' && $udom ne '') { - if ($end < $now) { + if ($end > 0 && $end < $now) { $status = 'previous'; } elsif ($start > $now) { $status = 'future'; @@ -4492,6 +5492,154 @@ sub get_user_info { return; } +############################################### + +=pod + +=item * &get_user_quota() + +Retrieves quota assigned for storage of portfolio files for a user + +Incoming parameters: +1. user's username +2. user's domain + +Returns: +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). +3. (Optional) - User's institutional status (e.g., faculty, staff + or student - types as defined in localenroll::inst_usertypes + for user's domain, which determines default quota for user. +4. (Optional) - Default quota which would apply to the user. + +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. + +=cut + +############################################### + + +sub get_user_quota { + my ($uname,$udom) = @_; + my ($quota,$quotatype,$settingstatus,$defquota); + if (!defined($udom)) { + $udom = $env{'user.domain'}; + } + if (!defined($uname)) { + $uname = $env{'user.name'}; + } + if (($udom eq '' || $uname eq '') || + ($udom eq 'public') && ($uname eq 'public')) { + $quota = 0; + $quotatype = 'default'; + $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'; + } else { + $quotatype = 'custom'; + } + } + if (wantarray) { + return ($quota,$quotatype,$settingstatus,$defquota); + } else { + return $quota; + } +} + +############################################### + +=pod + +=item * &default_quota() + +Retrieves default quota assigned for storage of user portfolio files, +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. + +Returns: +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). + +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. + +=cut + +############################################### + + +sub default_quota { + my ($udom,$inststatus) = @_; + my ($defquota,$settingstatus); + my %quotahash = &Apache::lonnet::get_dom('configuration', + ['quota'],$udom); + if (ref($quotahash{'quota'}) eq 'HASH') { + if ($inststatus ne '') { + my @statuses = split(/:/,$inststatus); + foreach my $item (@statuses) { + if ($quotahash{'quota'}{$item} ne '') { + if ($defquota eq '') { + $defquota = $quotahash{'quota'}{$item}; + $settingstatus = $item; + } elsif ($quotahash{'quota'}{$item} > $defquota) { + $defquota = $quotahash{'quota'}{$item}; + $settingstatus = $item; + } + } + } + } + if ($defquota eq '') { + $defquota = $quotahash{'quota'}{'default'}; + $settingstatus = 'default'; + } + } else { + $settingstatus = 'default'; + $defquota = 20; + } + if (wantarray) { + return ($defquota,$settingstatus); + } else { + return $defquota; + } +} + sub get_secgrprole_info { my ($cdom,$cnum,$needroles,$type) = @_; my %sections_count = &get_sections($cdom,$cnum); @@ -4529,8 +5677,238 @@ sub get_secgrprole_info { return (\@sections,\@groups,$allroles,$rolehash,$accesshash); } +sub user_picker { + my ($dom,$srch,$forcenewuser,$caller) = @_; + my $currdom = $dom; + my %curr_selected = ( + srchin => 'dom', + srchby => 'lastname', + ); + my $srchterm; + if (ref($srch) eq 'HASH') { + if ($srch->{'srchby'} ne '') { + $curr_selected{'srchby'} = $srch->{'srchby'}; + } + if ($srch->{'srchin'} ne '') { + $curr_selected{'srchin'} = $srch->{'srchin'}; + } + if ($srch->{'srchtype'} ne '') { + $curr_selected{'srchtype'} = $srch->{'srchtype'}; + } + if ($srch->{'srchdomain'} ne '') { + $currdom = $srch->{'srchdomain'}; + } + $srchterm = $srch->{'srchterm'}; + } + my %lt=&Apache::lonlocal::texthash( + 'usr' => 'Search criteria', + 'doma' => 'Domain/institution to search', + 'uname' => 'username', + 'lastname' => 'last name', + 'lastfirst' => 'last name, first name', + 'crs' => 'in this course', + 'dom' => 'in selected LON-CAPA domain', + 'alc' => 'all LON-CAPA', + 'instd' => 'in institutional directory for selected domain', + 'exact' => 'is', + 'contains' => 'contains', + 'begins' => 'begins with', + '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.", + 'yomc' => "You must choose a domain when using an institutional directory search.", + 'ymcd' => "You must choose a domain when using a domain search.", + 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.", + '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); + my $srchinsel = ' \n"; + + my $srchbysel = ' \n"; + + my $srchtypesel = ' \n"; + + my ($newuserscript,$new_user_create); + + if ($forcenewuser) { + if (ref($srch) eq 'HASH') { + if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) { + $new_user_create = '

&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" />

'; + } + } + + $newuserscript = <<"ENDSCRIPT"; + +function setSearch(createnew,callingForm) { + if (createnew == 1) { + for (var i=0; i +function validateEntry(callingForm) { + + var checkok = 1; + var srchin; + for (var i=0; i + +$new_user_create + +
$text"; } # Add the graphic @@ -738,12 +799,13 @@ ENDOUTPUT # now just updates the help link and generates a blue icon sub help_open_menu { my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) - = @_; - + = @_; $stayOnPage = 0 if (not defined $stayOnPage); + # only use pop-up help (stayOnPage == 0) + # if environment.remote is on (using remote control UI) if ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ) { - $stayOnPage=1; + $env{'environment.remote'} eq 'off' ) { + $stayOnPage=1; } my $output; if ($component_help) { @@ -764,15 +826,13 @@ sub help_open_menu { sub top_nav_help { my ($text) = @_; - $text = &mt($text); - - my $stayOnPage = + my $stay_on_page = ($env{'browser.interface'} eq 'textual' || $env{'environment.remote'} eq 'off' ); - my $link= ($stayOnPage) ? "javascript:helpMenu('display')" + my $link = ($stay_on_page) ? "javascript:helpMenu('display')" : "javascript:helpMenu('open')"; - my $banner_link = &update_help_link(undef,undef,undef,undef,$stayOnPage); + my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page); my $title = &mt('Get help'); @@ -800,7 +860,7 @@ sub help_menu_js { 'js_ready' => 1, 'add_entries' => { 'border' => '0', - 'rows' => "105,*",},}); + 'rows' => "110,*",},}); my $end_page = &Apache::loncommon::end_page({'frameset' => 1, 'js_ready' => 1,}); @@ -1014,8 +1074,65 @@ sub changable_area { =pod -=back +=item * resize_textarea_js + +emits the needed javascript to resize a textarea to be as big as possible + +creates a function resize_textrea that takes two IDs first should be +the id of the element to resize, second should be the id of a div that +surrounds everything that comes after the textarea, this routine needs +to be attached to the for the onload and onresize events. + + +=cut + +sub resize_textarea_js { + return <<"RESIZE"; + +RESIZE + +} + +=pod +=back + =head1 Excel and CSV file utility routines =over 4 @@ -1149,7 +1266,7 @@ sub create_workbook { =item * create_text_file -Create a file to write to and eventually make available to the usre. +Create a file to write to and eventually make available to the user. If file creation fails, outputs an error message on the request object and return undefs. @@ -1190,41 +1307,19 @@ sub create_text_file { ## Home server \n"; + ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom; + if ($showdomdesc) { + if ($dom ne '') { + my $domdesc = &Apache::lonnet::domain($dom,'description'); + if ($domdesc ne '') { + $selectdomain .= ' ('.$domdesc.')'; + } + } + } + $selectdomain .= "\n"; } $selectdomain.=""; return $selectdomain; @@ -1374,30 +1511,6 @@ sub select_dom_form { =pod -=item * get_library_servers($domain) - -Returns a hash which contains keys like '103l3' and values like -'kirk.lite.msu.edu'. All of the keys will be for machines in the -given $domain. - -=cut - -#------------------------------------------- -sub get_library_servers { - my $domain = shift; - my %library_servers; - foreach my $hostid (keys(%Apache::lonnet::libserv)) { - if ($Apache::lonnet::hostdom{$hostid} eq $domain) { - $library_servers{$hostid} = $Apache::lonnet::hostname{$hostid}; - } - } - return %library_servers; -} - -#------------------------------------------- - -=pod - =item * home_server_option_list($domain) returns a string which contains an
Transaction '.$version.''.&unescape($value).' '.$value.' 
Current'.$value.' 
'.$lt{'cour'}.''.$lt{'dura'}.''.$lt{'blse'}.'
'.$courseinfo{'description'}.''.$openblock.' to '.$closeblock.''.$fullname.'
+ + + + + + + + + +
$lt{'doma'}:$domform
$lt{'usr'}:$srchbysel + $srchtypesel + + $srchinsel +
+
+END_BLOCK + + return $output; +} + =pod +=back + +=head1 HTTP Helpers + +=over 4 + =item * get_unprocessed_cgi($query,$possible_names) Modify the %env hash to contain unprocessed CGI form parameters held in @@ -4666,7 +6044,7 @@ sub get_env_multiple { =pod -=back +=back =head1 CSV Upload/Handling functions @@ -4780,23 +6158,50 @@ sub record_sep { $i++; } } else { - my @allfields=split(/\,/,$record); + my $separator=','; + if ($env{'form.upfiletype'} eq 'semisv') { + $separator=';'; + } my $i=0; - my $j; - for ($j=0;$j<=$#allfields;$j++) { - my $field=$allfields[$j]; - if ($field=~/^\s*(\"|\')/) { - my $delimiter=$1; - while (($field!~/$delimiter$/) && ($j<$#allfields)) { - $j++; - $field.=','.$allfields[$j]; - } - $field=~s/^\s*$delimiter//; - $field=~s/$delimiter\s*$//; +# the character we are looking for to indicate the end of a quote or a record + my $looking_for=$separator; +# do not add the characters to the fields + my $ignore=0; +# we just encountered a separator (or the beginning of the record) + my $just_found_separator=1; +# store the field we are working on here + my $field=''; +# work our way through all characters in record + foreach my $character ($record=~/(.)/g) { + if ($character eq $looking_for) { + if ($character ne $separator) { +# Found the end of a quote, again looking for separator + $looking_for=$separator; + $ignore=1; + } else { +# Found a separator, store away what we got + $components{&takeleft($i)}=$field; + $i++; + $just_found_separator=1; + $ignore=0; + $field=''; + } + next; } - $components{&takeleft($i)}=$field; - $i++; +# single or double quotation marks after a separator indicate beginning of a quote +# we are now looking for the end of the quote and need to ignore separators + if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) { + $looking_for=$character; + next; + } +# ignore would be true after we reached the end of a quote + if ($ignore) { next; } + if (($just_found_separator) && ($character=~/\s/)) { next; } + $field.=$character; + $just_found_separator=0; } +# catch the very last entry, since we never encountered the separator + $components{&takeleft($i)}=$field; } return %components; } @@ -4818,6 +6223,7 @@ the file type. sub upfile_select_html { my %Types = ( csv => &mt('CSV (comma separated values, spreadsheet)'), + semisv => &mt('Semicolon separated values'), space => &mt('Space separated'), tab => &mt('Tabulator separated'), # xml => &mt('HTML/XML'), @@ -5472,16 +6878,19 @@ Returns: both routines return nothing ####################################################### ####################################################### sub store_course_settings { + return &store_settings($env{'request.course.id'},@_); +} + +sub store_settings { # save to the environment # appenv the same items, just to be safe - my $courseid = $env{'request.course.id'}; my $udom = $env{'user.domain'}; my $uname = $env{'user.name'}; - my ($prefix,$Settings) = @_; + my ($context,$prefix,$Settings) = @_; my %SaveHash; my %AppHash; while (my ($setting,$type) = each(%$Settings)) { - my $basename = join('.','internal',$courseid,$prefix,$setting); + my $basename = join('.','internal',$context,$prefix,$setting); my $envname = 'environment.'.$basename; if (exists($env{'form.'.$setting})) { # Save this value away @@ -5521,11 +6930,14 @@ sub store_course_settings { } sub restore_course_settings { - my $courseid = $env{'request.course.id'}; - my ($prefix,$Settings) = @_; + return &restore_settings($env{'request.course.id'},@_); +} + +sub restore_settings { + my ($context,$prefix,$Settings) = @_; while (my ($setting,$type) = each(%$Settings)) { next if (exists($env{'form.'.$setting})); - my $envname = 'environment.internal.'.$courseid.'.'.$prefix. + my $envname = 'environment.internal.'.$context.'.'.$prefix. '.'.$setting; if (exists($env{$envname})) { if ($type eq 'scalar') { @@ -5556,35 +6968,53 @@ sub commit_customrole { } sub commit_standardrole { - my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_; - my $output; - my $logmsg; + my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_; + my ($output,$logmsg,$linefeed); + if ($context eq 'auto') { + $linefeed = "\n"; + } else { + $linefeed = "
\n"; + } if ($three eq 'st') { - my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec); - if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) { + my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end, + $one,$two,$sec,$context); + if (($result =~ /^error/) || ($result eq 'not_in_class') || + ($result eq 'unknown_course')) { $output = "Error: $result\n"; } else { - $output = &mt('Assigning').' '.$three.' in '.$url. + $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url. ($start?', '.&mt('starting').' '.localtime($start):''). - ($end?', '.&mt('ending').' '.localtime($end):''). - ': '.$result.'
'. - &mt('Add to classlist').': ok
'; + ($end?', '.&mt('ending').' '.localtime($end):'').': '; + if ($context eq 'auto') { + $output .= $result.$linefeed.&mt('Add to classlist').': ok'; + } else { + $output .= ''.$result.''.$linefeed. + &mt('Add to classlist').': ok'; + } + $output .= $linefeed; } } else { $output = &mt('Assigning').' '.$three.' in '.$url. ($start?', '.&mt('starting').' '.localtime($start):''). - ($end?', '.&mt('ending').' '.localtime($end):'').': '. - &Apache::lonnet::assignrole( - $udom,$uname,$url,$three,$end,$start). - '
'; + ($end?', '.&mt('ending').' '.localtime($end):'').': '; + my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start); + if ($context eq 'auto') { + $output .= $result.$linefeed; + } else { + $output .= ''.$result.''.$linefeed; + } } return $output; } sub commit_studentrole { - my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_; - my $linefeed = '
'."\n"; - my $result; + my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_; + my ($result,$linefeed); + if ($context eq 'auto') { + $linefeed = "\n"; + } else { + $linefeed = '
'."\n"; + } if (defined($one) && defined($two)) { my $cid=$one.'_'.$two; my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid); @@ -5630,9 +7060,70 @@ sub commit_studentrole { ############################################################ ############################################################ +sub check_clone { + my ($args,$linefeed) = @_; + my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'}; + my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid); + my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom); + my $clonemsg; + my $can_clone = 0; + + if ($clonehome eq 'no_host') { + $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'}); + } else { + my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1}); + if ($env{'request.role.domain'} eq $args->{'clonedomain'}) { + $can_clone = 1; + } else { + my %clonehash = &Apache::lonnet::get('environment',['cloners'], + $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; + } else { + my %roleshash = + &Apache::lonnet::get_my_roles($args->{'ccuname'}, + $args->{'ccdomain'}, + 'userroles',['active'],['cc'], + [$args->{'clonedomain'}]); + if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) { + $can_clone = 1; + } 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'}); + } + } + } + } + return ($can_clone, $clonemsg, $cloneid, $clonehome); +} + sub construct_course { - my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname) = @_; + my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_; my $outcome; + my $linefeed = '
'."\n"; + if ($context eq 'auto') { + $linefeed = "\n"; + } + +# +# Are we cloning? +# + my ($can_clone, $clonemsg, $cloneid, $clonehome); + if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) { + ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed); + if ($context ne 'auto') { + if ($clonemsg ne '') { + $clonemsg = ''.$clonemsg.''; + } + } + $outcome .= $clonemsg.$linefeed; + + if (!$can_clone) { + return (0,$outcome); + } + } # # Open course @@ -5653,44 +7144,40 @@ sub construct_course { # Utils::Course. This needs to at least be output as a comment # if anyone ever decides to not show this, and Utils::Course::new # will need to be suitably modified. - $outcome .= &mt('New LON-CAPA [_1] ID: [_2]
',$crstype,$$courseid); + $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed; # # Check if created correctly # - ($$crsudom,$$crsunum)=($$courseid=~/^\/(\w+)\/(\w+)$/); + ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid); my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom); - $outcome .= &mt('Created on').': '.$crsuhome.'
'; -# -# Are we cloning? + $outcome .= &mt('Created on').': '.$crsuhome.$linefeed; + # - my $cloneid=''; - if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) { - $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'}; - my ($clonecrsudom,$clonecrsunum)=($cloneid=~/^\/(\w+)\/(\w+)$/); - my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom); - if ($clonehome eq 'no_host') { - $outcome .= - '
'.&mt('Attempting to clone non-existing [_1]',$crstype).' '.$cloneid.''; - } else { - $outcome .= - '
'.&mt('Cloning [_1] from [_2]',$crstype,$clonehome).''; - my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum); +# Do the cloning +# + if ($can_clone && $cloneid) { + $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome); + if ($context ne 'auto') { + $clonemsg = ''.$clonemsg.''; + } + $outcome .= $clonemsg.$linefeed; + my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum); # Copy all files - &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid); + &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid); # Restore URL - $cenv{'url'}=$oldcenv{'url'}; + $cenv{'url'}=$oldcenv{'url'}; # Restore title - $cenv{'description'}=$oldcenv{'description'}; + $cenv{'description'}=$oldcenv{'description'}; # restore grading mode - if (defined($oldcenv{'grading'})) { - $cenv{'grading'}=$oldcenv{'grading'}; - } -# Mark as cloned - $cenv{'clonedfrom'}=$cloneid; - delete($cenv{'default_enrollment_start_date'}); - delete($cenv{'default_enrollment_end_date'}); + if (defined($oldcenv{'grading'})) { + $cenv{'grading'}=$oldcenv{'grading'}; } +# Mark as cloned + $cenv{'clonedfrom'}=$cloneid; + delete($cenv{'default_enrollment_start_date'}); + delete($cenv{'default_enrollment_end_date'}); } + # # Set environment (will override cloned, if existing) # @@ -5794,11 +7281,24 @@ sub construct_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' ); - $outcome .= ''.$lt{'tclb'}.' ('.$cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.' ('.$lt{'adby'}.').
    '."\n"; - foreach (@badclasses) { - $outcome .= "
  • $_
  • \n"; - } - $outcome .= "


\n"; + my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}. + ' ('.$lt{'adby'}.')'; + if ($context eq 'auto') { + $outcome .= $badclass_msg.$linefeed; + $outcome .= '
'.$badclass_msg.$linefeed.'
    '."\n"; + foreach my $item (@badclasses) { + if ($context eq 'auto') { + $outcome .= " - $item\n"; + } else { + $outcome .= "
  • $item
  • \n"; + } + } + if ($context eq 'auto') { + $outcome .= $linefeed; + } else { + $outcome .= "


\n"; + } + } } if ($args->{'no_end_date'}) { $args->{'endaccess'} = 0; @@ -5814,8 +7314,13 @@ sub construct_course { $cenv{'internal.autharg'} = $args->{'autharg'}; if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) { if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') { - $outcome .= ''. - &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student').'

'; + my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student'); + if ($context eq 'auto') { + $outcome .= $krb_msg; + } else { + $outcome .= ''.$krb_msg.''; + } + $outcome .= $linefeed; } } if (($args->{'ccdomain'}) && ($args->{'ccuname'})) { @@ -5839,9 +7344,11 @@ sub construct_course { # if specified, key authority is not course, but user # only active if keyaccess is yes if ($args->{'keyauth'}) { - $args->{'keyauth'}=~s/[^\w\@]//g; - if ($args->{'keyauth'}) { - $cenv{'keyauth'}=$args->{'keyauth'}; + my ($user,$domain) = split(':',$args->{'keyauth'}); + $user = &LONCAPA::clean_username($user); + $domain = &LONCAPA::clean_username($domain); + if ($user ne '' && $domain ne '') { + $cenv{'keyauth'}=$user.':'.$domain; } } @@ -5869,8 +7376,8 @@ sub construct_course { # By default, use standard grading if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; } - $outcome .= ('
'.&mt('Setting environment').': '. - &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).'
'); + $outcome .= $linefeed.&mt('Setting environment').': '. + &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed; # # Open all assignments # @@ -5880,7 +7387,7 @@ sub construct_course { $storeunder.'.type' => 'date_start'); $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput - ('resourcedata',\%storecontent,$$crsudom,$$crsunum).'
'; + ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed; } # # Set first page @@ -5907,9 +7414,10 @@ sub construct_course { (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1); if ($errtext) { $fatal=2; } - $outcome .= ($fatal?$errtext:'write ok').'
'; + $outcome .= ($fatal?$errtext:'write ok').$linefeed; } - return $outcome; + + return (1,$outcome); } ############################################################ @@ -5938,7 +7446,7 @@ sub group_term { sub icon { my ($file)=@_; - my $curfext = (split(/\./,$file))[-1]; + my $curfext = lc((split(/\./,$file))[-1]); my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif'; my $embstyle = &Apache::loncommon::fileembstyle($curfext); if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) { @@ -5952,10 +7460,27 @@ sub icon { return &lonhttpdurl($iconname); } -sub lonhttpdurl { - my ($url)=@_; +sub lonhttpd_port { my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'}; if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; } + # IE doesn't like a secure page getting images from a non-secure + # port (when logging we haven't parsed the browser type so default + # back to secure + if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer') + && $ENV{'SERVER_PORT'} == 443) { + return 443; + } + return $lonhttpd_port; + +} + +sub lonhttpdurl { + my ($url)=@_; + + my $lonhttpd_port = &lonhttpd_port(); + if ($lonhttpd_port == 443) { + return 'https://'.$ENV{'SERVER_NAME'}.$url; + } return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url; } @@ -5991,6 +7516,171 @@ sub escape_url { my $lastitem = &escape(pop(@urlslices)); return join('/',@urlslices).'/'.$lastitem; } + +# -------------------------------------------------------- Initliaze user login +sub init_user_environment { + my ($r, $username, $domain, $authhost, $form, $args) = @_; + my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'}; + + my $public=($username eq 'public' && $domain eq 'public'); + +# See if old ID present, if so, remove + + my ($filename,$cookie,$userroles); + my $now=time; + + if ($public) { + my $max_public=100; + my $oldest; + my $oldest_time=0; + for(my $next=1;$next<=$max_public;$next++) { + if (-e $lonids."/publicuser_$next.id") { + my $mtime=(stat($lonids."/publicuser_$next.id"))[9]; + if ($mtime<$oldest_time || !$oldest_time) { + $oldest_time=$mtime; + $oldest=$next; + } + } else { + $cookie="publicuser_$next"; + last; + } + } + if (!$cookie) { $cookie="publicuser_$oldest"; } + } else { + # if this isn't a robot, kill any existing non-robot sessions + if (!$args->{'robot'}) { + opendir(DIR,$lonids); + while ($filename=readdir(DIR)) { + if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) { + unlink($lonids.'/'.$filename); + } + } + closedir(DIR); + } +# Give them a new cookie + my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'} + : $now); + $cookie="$username\_$id\_$domain\_$authhost"; + +# Initialize roles + + $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost); + } +# ------------------------------------ Check browser type and MathML capability + + my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml, + $clientunicode,$clientos) = &decode_user_agent($r); + +# -------------------------------------- Any accessibility options to remember? + if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) { + foreach my $option ('imagesuppress','appletsuppress', + 'embedsuppress','fontenhance','blackwhite') { + if ($form->{$option} eq 'true') { + &Apache::lonnet::put('environment',{$option => 'on'}, + $domain,$username); + } else { + &Apache::lonnet::del('environment',[$option], + $domain,$username); + } + } + } +# ------------------------------------------------------------- Get environment + + my %userenv = &Apache::lonnet::dump('environment',$domain,$username); + my ($tmp) = keys(%userenv); + if ($tmp !~ /^(con_lost|error|no_such_host)/i) { + # default remote control to off + if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; } + } else { + undef(%userenv); + } + if (($userenv{'interface'}) && (!$form->{'interface'})) { + $form->{'interface'}=$userenv{'interface'}; + } + $env{'environment.remote'}=$userenv{'remote'}; + if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; } + +# --------------- Do not trust query string to be put directly into environment + foreach my $option ('imagesuppress','appletsuppress', + 'embedsuppress','fontenhance','blackwhite', + 'interface','localpath','localres') { + $form->{$option}=~s/[\n\r\=]//gs; + } +# --------------------------------------------------------- Write first profile + + { + my %initial_env = + ("user.name" => $username, + "user.domain" => $domain, + "user.home" => $authhost, + "browser.type" => $clientbrowser, + "browser.version" => $clientversion, + "browser.mathml" => $clientmathml, + "browser.unicode" => $clientunicode, + "browser.os" => $clientos, + "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'}, + "request.course.fn" => '', + "request.course.uri" => '', + "request.course.sec" => '', + "request.role" => 'cm', + "request.role.adv" => $env{'user.adv'}, + "request.host" => $ENV{'REMOTE_ADDR'},); + + if ($form->{'localpath'}) { + $initial_env{"browser.localpath"} = $form->{'localpath'}; + $initial_env{"browser.localres"} = $form->{'localres'}; + } + + if ($public) { + $initial_env{"environment.remote"} = "off"; + } + if ($form->{'interface'}) { + $form->{'interface'}=~s/\W//gs; + $initial_env{"browser.interface"} = $form->{'interface'}; + $env{'browser.interface'}=$form->{'interface'}; + foreach my $option ('imagesuppress','appletsuppress', + 'embedsuppress','fontenhance','blackwhite') { + if (($form->{$option} eq 'true') || + ($userenv{$option} eq 'on')) { + $initial_env{"browser.$option"} = "on"; + } + } + } + + $env{'user.environment'} = "$lonids/$cookie.id"; + + if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id", + &GDBM_WRCREAT(),0640)) { + &_add_to_env(\%disk_env,\%initial_env); + &_add_to_env(\%disk_env,\%userenv,'environment.'); + &_add_to_env(\%disk_env,$userroles); + if (ref($args->{'extra_env'})) { + &_add_to_env(\%disk_env,$args->{'extra_env'}); + } + untie(%disk_env); + } else { + &Apache::lonnet::logthis("WARNING: ". + 'Could not create environment storage in lonauth: '.$!.''); + return 'error: '.$!; + } + } + $env{'request.role'}='cm'; + $env{'request.role.adv'}=$env{'user.adv'}; + $env{'browser.type'}=$clientbrowser; + + return $cookie; + +} + +sub _add_to_env { + my ($idf,$env_data,$prefix) = @_; + while (my ($key,$value) = each(%$env_data)) { + $idf->{$prefix.$key} = $value; + $env{$prefix.$key} = $value; + } +} + + =pod =back