--- loncom/interface/loncommon.pm 2013/07/10 22:07:37 1.1137 +++ loncom/interface/loncommon.pm 2014/11/08 18:26:06 1.1199 @@ -1,7 +1,7 @@ # The LearningOnline Network with CAPA # a pile of common routines # -# $Id: loncommon.pm,v 1.1137 2013/07/10 22:07:37 raeburn Exp $ +# $Id: loncommon.pm,v 1.1199 2014/11/08 18:26:06 raeburn Exp $ # # Copyright Michigan State University Board of Trustees # @@ -69,12 +69,15 @@ use Apache::lontexconvert(); use Apache::lonclonecourse(); use Apache::lonuserutils(); use Apache::lonuserstate(); +use Apache::courseclassifier(); use LONCAPA qw(:DEFAULT :match); use DateTime::TimeZone; use DateTime::Locale::Catalog; use Text::Aspell; use Authen::Captcha; use Captcha::reCAPTCHA; +use Crypt::DES; +use DynaLoader; # for Crypt::DES version # ---------------------------------------------- Designs use vars qw(%defaultdesign); @@ -1313,8 +1316,10 @@ sub helpLatexCheatsheet { .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600) .''; unless ($not_author) { - $out .= ' ' - .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600) + $out .= '' + .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600) + .' ' + .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600) .''; } $out .= ''; # End cheatsheet @@ -1380,32 +1385,38 @@ sub top_nav_help { $text = &mt($text); my $stay_on_page = 1; - my $link = ($stay_on_page) ? "javascript:helpMenu('display')" - : "javascript:helpMenu('open')"; - my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page); - + my ($link,$banner_link); + unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) { + $link = ($stay_on_page) ? "javascript:helpMenu('display')" + : "javascript:helpMenu('open')"; + $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page); + } my $title = &mt('Get help'); - - return <<"END"; + if ($link) { + return <<"END"; $banner_link - $text +$text END + } else { + return ' '.$text.' '; + } } sub help_menu_js { - my ($text) = @_; + my ($httphost) = @_; my $stayOnPage = 1; my $width = 620; my $height = 600; my $helptopic=&general_help(); - my $details_link = '/adm/help/'.$helptopic.'.hlp'; + my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp'; my $nothing=&Apache::lonhtmlcommon::javascript_nothing(); my $start_page = &Apache::loncommon::start_page('Help Menu', undef, {'frameset' => 1, 'js_ready' => 1, + 'use_absolute' => $httphost, 'add_entries' => { - 'border' => '0', + 'border' => '0', 'rows' => "110,*",},}); my $end_page = &Apache::loncommon::end_page({'frameset' => 1, @@ -1435,9 +1446,10 @@ function helpMenu(target) { return; } function writeHelp(caller) { - caller.document.writeln('$start_page\\n\\n\\n$end_page') - caller.document.close() - caller.focus() + caller.document.writeln('$start_page\\n\\n'); + caller.document.writeln('\\n$end_page'); + caller.document.close(); + caller.focus(); } // END LON-CAPA Internal --> // ]]> @@ -1749,8 +1761,6 @@ RESIZE =head1 Excel and CSV file utility routines -=over 4 - =cut ############################################################### @@ -1758,6 +1768,8 @@ RESIZE =pod +=over 4 + =item * &csv_translate($text) Translate $text to allow it to be output as a 'comma separated values' @@ -2351,6 +2363,10 @@ Outputs: =item * $clientmobile +=item * $clientinfo + +=item * $clientosversion + =back =back @@ -2370,8 +2386,9 @@ sub decode_user_agent { my $clientmathml=''; my $clientunicode='0'; my $clientmobile=0; + my $clientosversion=''; for (my $i=0;$i<=$#browsertype;$i++) { - my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]); + my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]); if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) { $clientbrowser=$bname; $httpbrowser=~/$vreg/i; @@ -2381,6 +2398,7 @@ sub decode_user_agent { } } my $clientos='unknown'; + my $clientinfo; if (($httpbrowser=~/linux/i) || ($httpbrowser=~/unix/i) || ($httpbrowser=~/ux/i) || @@ -2390,13 +2408,24 @@ sub decode_user_agent { if ($httpbrowser=~/next/i) { $clientos='next'; } if (($httpbrowser=~/mac/i) || ($httpbrowser=~/powerpc/i)) { $clientos='mac'; } - if ($httpbrowser=~/win/i) { $clientos='win'; } + if ($httpbrowser=~/win/i) { + $clientos='win'; + if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) { + $clientosversion = $1; + } + } if ($httpbrowser=~/embed/i) { $clientos='pda'; } if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) { $clientmobile=lc($1); } + if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) { + $clientinfo = 'firefox-'.$1; + } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) { + $clientinfo = 'chromeframe-'.$1; + } return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml, - $clientunicode,$clientos,$clientmobile); + $clientunicode,$clientos,$clientmobile,$clientinfo, + $clientosversion); } ############################################################### @@ -3066,6 +3095,8 @@ sub get_related_words { =pod +=back + =head1 Spell checking =over 4 @@ -3099,12 +3130,6 @@ Note: This sub assumes that aspell is in =cut -=pod - -=back - -=cut - sub check_spelling { my ($wordlist, $language) = @_; my @misspellings; @@ -3320,7 +3345,7 @@ sub screenname { # ------------------------------------------------------------- Confirm Wrapper =pod -=item confirmwrapper +=item * &confirmwrapper($message) Wrap messages about completion of operation in box @@ -3736,7 +3761,7 @@ sub user_lang { =over 4 =item * &get_previous_attempt($symb, $username, $domain, $course, - $getattempt, $regexp, $gradesub) + $getattempt, $regexp, $gradesub, $usec, $identifier) Return string with previous attempt on problem. Arguments: @@ -3758,6 +3783,11 @@ Return string with previous attempt on p =item * $gradesub: routine that processes the string if it matches $regexp +=item * $usec: section of the desired student + +=item * $identifier: counter for student (multiple students one problem) or + problem (one student; whole sequence). + =back The output string is a table containing all desired attempts, if any. @@ -3765,7 +3795,7 @@ The output string is a table containing =cut sub get_previous_attempt { - my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_; + my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_; my $prevattempts=''; no strict 'refs'; if ($symb) { @@ -3781,7 +3811,7 @@ sub get_previous_attempt { } $prevattempts=&start_data_table().&start_data_table_header_row(); $prevattempts.=''.&mt('History').''; - my (%typeparts,%lasthidden); + my (%typeparts,%lasthidden,%regraded,%hidestatus); my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'}); foreach my $key (sort(keys(%lasthash))) { my ($ign,@parts) = split(/\./,$key); @@ -3798,6 +3828,17 @@ sub get_previous_attempt { $lasthidden{$ign.'.'.$id} = 1; } } + if ($identifier ne '') { + my $id = join(',',@parts); + if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb, + $domain,$username,$usec,undef,$course) =~ /^no/) { + $hidestatus{$ign.'.'.$id} = 1; + } + } + } elsif ($data eq 'regrader') { + if (($identifier ne '') && (@parts)) { + $regraded{$parts[-1]} = 1; + } } } else { if ($#parts == 0) { @@ -3809,17 +3850,58 @@ sub get_previous_attempt { } $prevattempts.=&end_data_table_header_row(); if ($getattempt eq '') { + my (%solved,%resets,%probstatus); for ($version=1;$version<=$returnhash{'version'};$version++) { - my @hidden; + if ($identifier ne '') { + foreach my $part (keys(%regraded)) { + if (($returnhash{$version.':resource.'.$part.'.regrader'}) && + ($returnhash{$version.':resource.'.$part.'.tries'} eq '') && + ($returnhash{$version.':resource.'.$part.'.award'} eq '')) { + push(@{$resets{$part}},$version); + } + } + } + my (@hidden,@unsolved); if (%typeparts) { foreach my $id (keys(%typeparts)) { - if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) { + if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || + ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) { push(@hidden,$id); + } elsif ($identifier ne '') { + unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') || + ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') || + ($hidestatus{$id})) { + next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$id\E$/,@{$resets{$id}})); + if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') { + push(@{$solved{$id}},$version); + } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') && + (ref($solved{$id}) eq 'ARRAY')) { + my $skip; + if (ref($resets{$id}) eq 'ARRAY') { + foreach my $reset (@{$resets{$id}}) { + if ($reset > $solved{$id}[-1]) { + $skip=1; + last; + } + } + } + unless ($skip) { + my ($ign,$partslist) = split(/\./,$id,2); + push(@unsolved,$partslist); + } + } + } } } } $prevattempts.=&start_data_table_row(). - ''.&mt('Transaction [_1]',$version).''; + ''.&mt('Transaction [_1]',$version); + if (@unsolved) { + $prevattempts .= ''; + } + $prevattempts .= ''; if (@hidden) { foreach my $key (sort(keys(%lasthash))) { next if ($key =~ /\.foilorder$/); @@ -3879,7 +3961,7 @@ sub get_previous_attempt { if ($key =~/$regexp$/ && (defined &$gradesub)) { $value = &$gradesub($value); } - $prevattempts.=''.$value.' '; + $prevattempts.=''. $value.' '; } else { $prevattempts.=' '; } @@ -3895,7 +3977,7 @@ sub get_previous_attempt { if ($key =~/$regexp$/ && (defined &$gradesub)) { $value = &$gradesub($value); } - $prevattempts.=''.$value.' '; + $prevattempts.=''.$value.' '; } } $prevattempts.= &end_data_table_row().&end_data_table(); @@ -3916,11 +3998,13 @@ sub get_previous_attempt { sub format_previous_attempt_value { my ($key,$value) = @_; if (($key =~ /timestamp/) || ($key=~/duedate/)) { - $value = &Apache::lonlocal::locallocaltime($value); + $value = &Apache::lonlocal::locallocaltime($value); } elsif (ref($value) eq 'ARRAY') { - $value = '('.join(', ', @{ $value }).')'; + $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&'); } elsif ($key =~ /answerstring$/) { my %answers = &Apache::lonnet::str2hash($value); + my @answer = %answers; + %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer; my @anskeys = sort(keys(%answers)); if (@anskeys == 1) { my $answer = $answers{$anskeys[0]}; @@ -3943,7 +4027,7 @@ sub format_previous_attempt_value { } } } else { - $value = &unescape($value); + $value = &HTML::Entities::encode(&unescape($value), '"<>&'); } return $value; } @@ -4304,23 +4388,20 @@ sub findallcourses { ############################################### sub blockcheck { - my ($setters,$activity,$uname,$udom,$url) = @_; + my ($setters,$activity,$uname,$udom,$url,$is_course) = @_; - if (!defined($udom)) { + if (defined($udom) && defined($uname)) { + # If uname and udom are for a course, check for blocks in the course. + if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) { + my ($startblock,$endblock,$triggerblock) = + &get_blocks($setters,$activity,$udom,$uname,$url); + return ($startblock,$endblock,$triggerblock); + } + } else { $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 ($startblock,$endblock,$triggerblock) = - &get_blocks($setters,$activity,$udom,$uname,$url); - return ($startblock,$endblock,$triggerblock); - } - my $startblock = 0; my $endblock = 0; my $triggerblock = ''; @@ -4330,7 +4411,8 @@ sub blockcheck { # 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'})) { + $activity eq 'groups' || $activity eq 'printout') && + ($env{'request.course.id'})) { foreach my $key (keys(%live_courses)) { if ($key ne $env{'request.course.id'}) { delete($live_courses{$key}); @@ -4594,12 +4676,12 @@ sub parse_block_record { } sub blocking_status { - my ($activity,$uname,$udom,$url) = @_; + my ($activity,$uname,$udom,$url,$is_course) = @_; my %setters; # check for active blocking my ($startblock,$endblock,$triggerblock) = - &blockcheck(\%setters,$activity,$uname,$udom,$url); + &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course); my $blocked = 0; if ($startblock && $endblock) { $blocked = 1; @@ -5120,6 +5202,7 @@ sub bodytag { $public = 1; } if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } + my $httphost = $args->{'use_absolute'}; $function = &get_users_function() if (!$function); my $img = &designparm($function.'.img',$domain); @@ -5135,7 +5218,10 @@ sub bodytag { @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; # role and realm - my ($role,$realm) = split(/\./,$env{'request.role'},2); + my ($role,$realm) = split(m{\./},$env{'request.role'},2); + if ($realm) { + $realm = '/'.$realm; + } if ($role eq 'ca') { my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$}); $realm = &plainname($rname,$rdom); @@ -5192,7 +5278,7 @@ sub bodytag { # } $bodytag .= Apache::lonhtmlcommon::scripttag( - Apache::lonmenu::utilityfunctions(), 'start'); + Apache::lonmenu::utilityfunctions($httphost), 'start'); my ($left,$right) = Apache::lonmenu::primary_menu(); @@ -5216,9 +5302,13 @@ sub bodytag { } $bodytag .= qq|
$realm $dc_info
|; + #if directed to not display the secondary menu, don't. + if ($args->{'no_secondary_menu'}) { + return $bodytag; + } #don't show menus for public users if (!$public){ - $bodytag .= Apache::lonmenu::secondary_menu(); + $bodytag .= Apache::lonmenu::secondary_menu($httphost); $bodytag .= Apache::lonmenu::serverform(); $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); if ($env{'request.state'} eq 'construct') { @@ -5278,7 +5368,7 @@ sub make_attr_string { } my $attr_string; - foreach my $attr (keys(%$attr_ref)) { + foreach my $attr (sort(keys(%$attr_ref))) { $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" '; } return $attr_string; @@ -6492,6 +6582,14 @@ div.LC_edit_problem_saves { white-space: nowrap; } +.LC_edit_problem_latexhelper{ + text-align: right; +} + +#LC_edit_problem_colorful div{ + margin-left: 40px; +} + img.stift { border-width: 0; vertical-align: middle; @@ -7257,6 +7355,7 @@ sub headtag { my $function = $args->{'function'} || &get_users_function(); my $domain = $args->{'domain'} || &determinedomain(); my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain); + my $httphost = $args->{'use_absolute'}; my $url = join(':',$env{'user.name'},$env{'user.domain'}, $Apache::lonnet::perlvar{'lonVersion'}, #time(), @@ -7267,9 +7366,12 @@ sub headtag { my $result = ''. - &font_settings(); + &font_settings($args); - my $inhibitprint = &print_suppression(); + my $inhibitprint; + if ($args->{'print_suppress'}) { + $inhibitprint = &print_suppression(); + } if (!$args->{'frameset'}) { $result .= &Apache::lonhtmlcommon::htmlareaheaders(); @@ -7280,7 +7382,7 @@ sub headtag { if (!$args->{'no_nav_bar'} && !$args->{'only_body'} && !$args->{'frameset'}) { - $result .= &help_menu_js(); + $result .= &help_menu_js($httphost); $result.=&modal_window(); $result.=&togglebox_script(); $result.=&wishlist_window(); @@ -7315,7 +7417,11 @@ ADDMETA } if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } $result .= ' LON-CAPA '.$title.'' - .'' + .'{'frameset'}) { + $result .= ' /'; + } + $result .= '>' .$inhibitprint .$head_extra; if ($env{'browser.mobile'}) { @@ -7332,15 +7438,21 @@ ADDMETA Returns neccessary to set the proper encoding -Inputs: none +Inputs: optional reference to HASH -- $args passed to &headtag() =cut sub font_settings { + my ($args) = @_; my $headerstring=''; - if (!$env{'browser.mathml'} && $env{'browser.unicode'}) { - $headerstring.= - ''; + if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) || + ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) { + $headerstring.= + '{'frameset'}) { + $headerstring.= ' /'; + } + $headerstring .= '>'."\n"; } return $headerstring; } @@ -7385,7 +7497,7 @@ sub print_suppression { } my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; - my $blocked = &blocking_status('printout',$cnum,$cdom); + my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1); if ($blocked) { my $checkrole = "cm./$cdom/$cnum"; if ($env{'request.course.sec'} ne '') { @@ -7432,6 +7544,7 @@ Inputs: none =cut sub xml_begin { + my ($is_frameset) = @_; my $output=''; if ($env{'browser.mathml'}) { @@ -7443,9 +7556,12 @@ sub xml_begin { .'' .''; + } elsif ($is_frameset) { + $output=''."\n". + ''."\n"; } else { - $output='' - .''; + $output=''."\n". + ''."\n"; } return $output; } @@ -7512,7 +7628,7 @@ sub start_page { my ($result,@advtools); if (! exists($args->{'skip_phases'}{'head'}) ) { - $result .= &xml_begin() . &headtag($title, $head_extra, $args); + $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args); } if (! exists($args->{'skip_phases'}{'body'}) ) { @@ -7613,9 +7729,11 @@ function set_wishlistlink(title, path) { title = document.title; title = title.replace(/^LON-CAPA /,''); } + title = encodeURIComponent(title); if (!path) { path = location.pathname; } + path = encodeURIComponent(path); Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path, 'wishlistNewLink','width=560,height=350,scrollbars=0'); } @@ -7656,12 +7774,12 @@ var modalWindow = { $(".LCmodal-overlay").click(function(){modalWindow.close();}); } }; - var openMyModal = function(source,width,height,scrolling) + var openMyModal = function(source,width,height,scrolling,transparency,style) { modalWindow.windowId = "myModal"; modalWindow.width = width; modalWindow.height = height; - modalWindow.content = ""; modalWindow.open(); }; // END LON-CAPA Internal --> @@ -7671,16 +7789,18 @@ ENDMODAL } sub modal_link { - my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_; + my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_; unless ($width) { $width=480; } unless ($height) { $height=400; } unless ($scrolling) { $scrolling='yes'; } + unless ($transparency) { $transparency='true'; } + my $target_attr; if (defined($target)) { $target_attr = 'target="'.$target.'"'; } return <<"ENDLINK"; - + $linktext ENDLINK } @@ -7707,11 +7827,11 @@ sub modal_adhoc_inner { my ($funcname,$width,$height,$content)=@_; my $innerwidth=$width-20; $content=&js_ready( - &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}). - &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','modal'). - $content. + &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}). + &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1). + $content. &end_scrollbox(). - &end_page() + &end_page() ); return &modal_adhoc_script($funcname,$width,$height,$content); } @@ -7928,13 +8048,13 @@ sub validate_page { sub start_scrollbox { - my ($outerwidth,$width,$height,$id,$bgcolor)=@_; + my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_; unless ($outerwidth) { $outerwidth='520px'; } unless ($width) { $width='500px'; } unless ($height) { $height='200px'; } my ($table_id,$div_id,$tdcol); if ($id ne '') { - $table_id = " id='table_$id'"; + $table_id = ' id="table_'.$id.'"'; $div_id = ' id="div_'.$id.'"'; } if ($bgcolor ne '') { @@ -7942,20 +8062,8 @@ sub start_scrollbox { } my $nicescroll_js; if ($env{'browser.mobile'}) { - $nicescroll_js = ' - -'; + $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready); } - return <<"END"; $nicescroll_js @@ -7968,11 +8076,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); @@ -8599,11 +8794,11 @@ Incoming parameters: 2. user's domain 3. quota name - portfolio, author, or course (if no quota name provided, defaults to portfolio). -4. crstype - official, unofficial or community, if quota name is +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). @@ -8673,7 +8868,8 @@ sub get_user_quota { 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')) { + if (($crstype eq 'official') || ($crstype eq 'unofficial') || + ($crstype eq 'community') || ($crstype eq 'textbook')) { $defquota = $domdefs{$crstype.'quota'}; } if ($defquota eq '') { @@ -8707,6 +8903,7 @@ 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.) @@ -8717,21 +8914,20 @@ Incoming parameters: (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 ############################################### @@ -8780,6 +8976,11 @@ sub default_quota { $defquota = $quotahash{'quotas'}{'default'}; } $settingstatus = 'default'; + if ($defquota eq '') { + if ($quotaname eq 'author') { + $defquota = 500; + } + } } } else { $settingstatus = 'default'; @@ -8804,28 +9005,31 @@ sub default_quota { 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, +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: 6 +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. + otherwise return null. + +=back =cut sub excess_filesize_warning { - my ($uname,$udom,$context,$filename,$filesize,$action) = @_; + my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_; my $current_disk_usage = 0; - my $disk_quota = &get_user_quota($uname,$udom,$context); #expressed in MB + 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); @@ -8836,10 +9040,10 @@ sub excess_filesize_warning { } $disk_quota = int($disk_quota * 1000); if (($current_disk_usage + $filesize) > $disk_quota) { - return '

'. + 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.', + ''.$filename.'',$filesize).'

'. + '

'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.', $disk_quota,$current_disk_usage). '

'; } @@ -9292,7 +9496,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'); @@ -9690,11 +9901,10 @@ 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'); - my ($navmap,$cdom,$cnum); if ($env{'request.course.id'}) { if ($actionurl eq '/adm/dependencies') { $navmap = Apache::lonnavmaps::navmap->new(); @@ -9756,7 +9966,15 @@ sub ask_for_embedded_content { ($path) = ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); } - $fileloc = &Apache::lonnet::filelocation('',$toplevel); + 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)"); @@ -9778,17 +9996,18 @@ sub ask_for_embedded_content { } else { $embed_file = $file; } - my $absolutepath; + 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 '') { @@ -9805,9 +10024,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; } } } @@ -10181,6 +10400,46 @@ sub ask_for_embedded_content { 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') && @@ -10305,7 +10564,8 @@ 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)))) { @@ -10569,6 +10829,7 @@ sub modify_html_refs { 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}); @@ -10744,11 +11005,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); } } @@ -10757,21 +11018,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); } } @@ -10862,16 +11123,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; @@ -10883,7 +11194,7 @@ sub decompress_form { function camtasiaToggle() { for (var i=0; i'. ''.$lt{'proa'}.' 
'. @@ -11069,7 +11380,7 @@ sub decompress_uploaded_file { sub process_decompression { my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_; my ($dir,$error,$warning,$output); - if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) { + 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'); @@ -11179,6 +11490,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'} = []; @@ -11197,12 +11509,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'; @@ -11929,7 +12244,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, @@ -12039,6 +12354,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); } } @@ -12047,6 +12365,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') { @@ -12087,6 +12408,9 @@ sub get_turnedin_filepath { $restitle = time; } } + if (length($restitle) > 12) { + $restitle = substr($restitle,0,12); + } push(@pathitems,$restitle); $path .= join('/',@pathitems); } @@ -13024,16 +13348,20 @@ sub restore_settings { =item * &build_recipient_list() -Build recipient lists for five types of e-mail: +Build recipient lists for following types of e-mail: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors -(d) Help requests, (e) Course requests needing approval, generated by -lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and -loncoursequeueadmin.pm respectively. +(d) Help requests, (e) Course requests needing approval, (f) loncapa +module change checking, student/employee ID conflict checks, as +generated by lonerrorhandler.pm, CHECKRPMS, loncron, +lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively. Inputs: defmail (scalar - email address of default recipient), -mailing type (scalar - errormail, packagesmail, or helpdeskmail), +mailing type (scalar: errormail, packagesmail, helpdeskmail, +requestsmail, updatesmail, or idconflictsmail). + defdom (domain for which to retrieve configuration settings), + origmail (scalar - email address of recipient from loncapa.conf, i.e., predates configuration by DC via domainprefs.pm @@ -13229,7 +13557,7 @@ sub extract_categories { =pod -=item *&recurse_categories() +=item * &recurse_categories() Recursively used to generate breadcrumb trails for course categories. @@ -13300,7 +13628,7 @@ sub recurse_categories { =pod -=item *&assign_categories_table() +=item * &assign_categories_table() Create a datatable for display of hierarchical categories in a domain, with checkboxes to allow a course to be categorized. @@ -13377,7 +13705,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. @@ -13411,7 +13739,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; @@ -13443,6 +13771,12 @@ sub assign_category_rows { return $text; } +=pod + +=back + +=cut + ############################################################ ############################################################ @@ -13695,7 +14029,7 @@ 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') { @@ -13792,8 +14126,12 @@ sub construct_course { 'plc.users.denied', 'hidefromcat', 'checkforpriv', - 'categories'], + 'categories', + 'internal.uniquecode'], $$crsudom,$$crsunum); + if ($args->{'textbook'}) { + $cenv{'internal.textbook'} = $args->{'textbook'}; + } } # @@ -13977,6 +14315,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'; } @@ -14045,6 +14402,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; +} + ############################################################ ############################################################ @@ -14072,11 +14483,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); } @@ -14208,8 +14620,8 @@ sub init_user_environment { } # ------------------------------------ Check browser type and MathML capability - my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml, - $clientunicode,$clientos,$clientmobile) = &decode_user_agent($r); + my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode, + $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r); # ------------------------------------------------------------- Get environment @@ -14241,6 +14653,8 @@ sub init_user_environment { "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" => '', @@ -14260,6 +14674,12 @@ sub init_user_environment { $env{'browser.interface'}=$form->{'interface'}; } + if ($form->{'iptoken'}) { + my $lonhost = $r->dir_config('lonHostID'); + $initial_env{"user.noloadbalance"} = $lonhost; + $env{'user.noloadbalance'} = $lonhost; + } + my %is_adv = ( is_adv => $env{'user.adv'} ); my %domdef; unless ($domain eq 'public') { @@ -14272,7 +14692,7 @@ sub init_user_environment { undef,\%userenv,\%domdef,\%is_adv); } - foreach my $crstype ('official','unofficial','community') { + foreach my $crstype ('official','unofficial','community','textbook') { $userenv{'canrequest.'.$crstype} = &Apache::lonnet::usertools_access($username,$domain,$crstype, 'reload','requestcourses', @@ -14377,36 +14797,540 @@ 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},'<>&"'); + } + } + + # 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 = '"; + } + + my ($cloneableonlyform,$cloneabletitle); + if (exists($filter->{'cloneableonly'})) { + my $cloneableon = ''; + my $cloneableoff = ' checked="checked"'; + if ($filter->{'cloneableonly'}) { + $cloneableon = $cloneableoff; + $cloneableoff = ''; + } + $cloneableonlyform = ''.(' 'x3).''; + if ($formname eq 'ccrs') { + $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom); + } else { + $cloneabletitle = &mt('Cloneable by you'); + } + } + my $officialjs; + if ($crstype eq 'Course') { + if (exists($filter->{'instcodefilter'})) { +# if (($fixeddom) || ($formname eq 'requestcrs') || +# ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) { + if ($codedom) { + $officialjs = 1; + ($instcodeform,$jscript,$$numtitlesref) = + &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker', + $officialjs,$codetitlesref); + if ($jscript) { + $jscript = ''."\n"; + } + } + if ($instcodeform eq '') { + $instcodeform = + ''; + $instcodetitle = $lt{'ins'}; + } else { + $instcodetitle = $lt{'inc'}; + } + if ($fixeddom) { + $instcodetitle .= '
('.$codedom.')'; + } + } + } + my $output = qq| + + +|; + if ($formname eq 'modifycourse') { + $output .= ''."\n". + ''."\n"; + } elsif ($formname eq 'quotacheck') { + $output .= qq| + + +|; + } else { + my $name_input; + if ($cnameelement ne '') { + $name_input = ''; + } + $output .= qq| + + +$name_input +$roleelement +$multelement +$typeelement +|; + if ($formname eq 'portform') { + $output .= ''."\n"; } } - ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'}); - ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'}); + if ($fixeddom) { + $output .= ''."\n"; + } + $output .= "
\n".&Apache::lonhtmlcommon::start_pick_box(); + if ($sincefilterform) { + $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'}) + .$sincefilterform + .&Apache::lonhtmlcommon::row_closure(); + } + if ($createdfilterform) { + $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'}) + .$createdfilterform + .&Apache::lonhtmlcommon::row_closure(); + } + if ($domainselectform) { + $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'}) + .$domainselectform + .&Apache::lonhtmlcommon::row_closure(); + } + if ($typeselectform) { + if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) { + $output .= $typeselectform; + } else { + $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'}) + .$typeselectform + .&Apache::lonhtmlcommon::row_closure(); + } + } + if ($instcodeform) { + $output .= &Apache::lonhtmlcommon::row_title($instcodetitle) + .$instcodeform + .&Apache::lonhtmlcommon::row_closure(); + } + if (exists($filter->{'ownerfilter'})) { + $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}). + '
'.&mt('Username').'
'. + '
'.&mt('Domain').'
'. + $ownerdomselectform.'
'. + &Apache::lonhtmlcommon::row_closure(); + } + if (exists($filter->{'personfilter'})) { + $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}). + '
'.&mt('Username').'
'. + '
'.&mt('Domain').'
'. + $persondomselectform.'
'. + &Apache::lonhtmlcommon::row_closure(); + } + if (exists($filter->{'coursefilter'})) { + $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID')) + .'' + .&Apache::lonhtmlcommon::row_closure(); + } + if ($cloneableonlyform) { + $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle). + $cloneableonlyform.&Apache::lonhtmlcommon::row_closure(); + } + if (exists($filter->{'descriptfilter'})) { + $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'}) + .'' + .&Apache::lonhtmlcommon::row_closure(1); + } + $output .= &Apache::lonhtmlcommon::end_pick_box().'

'.$clonetext."\n". + ''."\n". + '

'."\n".''."\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). + + +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) = @_; + 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,$env{'form.cc_clone'}, + $filter->{'cloneableonly'}, + $createdbefore,$createdafter,undef, + $domcloner); + 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 + +=cut + + sub update_content_constraints { my ($cdom,$cnum,$chome,$cid) = @_; my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired'); @@ -14493,6 +15417,30 @@ sub parse_supplemental_title { 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) = @_; return unless ($symb); @@ -14522,7 +15470,7 @@ sub symb_to_docspath { my $thistitle = $res->title(); $path .= '&'. &Apache::lonhtmlcommon::entity_encode($thisurl).'&'. - &Apache::lonhtmlcommon::entity_encode($thistitle). + &escape($thistitle). ':'.$res->randompick(). ':'.$res->randomout(). ':'.$res->encrypted(). @@ -14538,7 +15486,7 @@ sub symb_to_docspath { } $path .= (($path ne '')? '&' : ''). &Apache::lonhtmlcommon::entity_encode($mapurl).'&'. - &Apache::lonhtmlcommon::entity_encode($maptitle). + &escape($maptitle). ':'.$mapresobj->randompick(). ':'.$mapresobj->randomout(). ':'.$mapresobj->encrypted(). @@ -14551,11 +15499,11 @@ sub symb_to_docspath { $maptitle = 'Main Content'; } $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'. - &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage; + &escape($maptitle).':::::'.$ispage; } unless ($mapurl eq 'default') { $path = 'default&'. - &Apache::lonhtmlcommon::entity_encode('Main Content'). + &escape('Main Content'). ':::::&'.$path; } return $path; @@ -14568,15 +15516,15 @@ sub captcha_display { if ($captcha eq 'original') { $output = &create_captcha(); unless ($output) { - $error = 'captcha'; + $error = 'captcha'; } } elsif ($captcha eq 'recaptcha') { $output = &create_recaptcha($pubkey); unless ($output) { - $error = 'recaptcha'; + $error = 'recaptcha'; } } - return ($output,$error); + return ($output,$error,$captcha); } sub captcha_response { @@ -14652,8 +15600,9 @@ sub create_captcha { if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') { $output = ''."\n". &mt('Type in the letters/numbers shown below').' '. - '
'. - ''; + ''. + '
'. + 'captcha'; last; } } @@ -14694,9 +15643,13 @@ sub check_captcha { sub create_recaptcha { my ($pubkey) = @_; + 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). + $captcha->get_html($pubkey,undef,$use_ssl). &mt('If either word is hard to read, [_1] will replace them.', 'reCAPTCHA refresh'). '

'; @@ -14719,11 +15672,102 @@ sub check_recaptcha { return $captcha_chk; } -=pod +sub emailusername_info { + my @fields = ('firstname','lastname','institution','web','location','officialemail'); + 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)', + ); + return (\@fields,\%titles); +} -=back +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 + } + 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 (); +} -=cut +# 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= + $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16)))); + $plaintext.= + $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16)))); + $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) ); + return $plaintext; +} 1; __END__;