--- loncom/interface/loncommon.pm 2012/06/01 12:02:10 1.1075.2.7 +++ loncom/interface/loncommon.pm 2012/11/16 16:54:45 1.1097 @@ -1,7 +1,7 @@ # The LearningOnline Network with CAPA # a pile of common routines # -# $Id: loncommon.pm,v 1.1075.2.7 2012/06/01 12:02:10 raeburn Exp $ +# $Id: loncommon.pm,v 1.1097 2012/11/16 16:54:45 bisitz Exp $ # # Copyright Michigan State University Board of Trustees # @@ -70,6 +70,9 @@ use Apache::lonclonecourse(); use LONCAPA qw(:DEFAULT :match); use DateTime::TimeZone; use DateTime::Locale::Catalog; +use Text::Aspell; +use Authen::Captcha; +use Captcha::reCAPTCHA; # ---------------------------------------------- Designs use vars qw(%defaultdesign); @@ -154,6 +157,7 @@ sub ssi_with_retries { # ----------------------------------------------- Filetypes/Languages/Copyright my %language; my %supported_language; +my %supported_codes; my %latex_language; # For choosing hyphenation in my %latex_language_bykey; # for choosing hyphenation from metadata my %cprtag; @@ -188,14 +192,15 @@ BEGIN { while (my $line = <$fh>) { next if ($line=~/^\#/); chomp($line); - my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line)); + my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line)); $language{$key}=$val.' - '.$enc; if ($sup) { $supported_language{$key}=$sup; + $supported_codes{$key} = $code; } if ($latex) { $latex_language_bykey{$key} = $latex; - $latex_language{$two} = $latex; + $latex_language{$code} = $latex; } } close($fh); @@ -657,7 +662,7 @@ if (!Array.prototype.indexOf) { var n = 0; if (arguments.length > 0) { n = Number(arguments[1]); - if (n !== n) { // shortcut for verifying if it's NaN + if (n !== n) { // shortcut for verifying if it is NaN n = 0; } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); @@ -885,10 +890,14 @@ sub check_uncheck_jscript { function checkAll(field) { if (field.length > 0) { for (i = 0; i < field.length; i++) { - field[i].checked = true ; + if (!field[i].disabled) { + field[i].checked = true; + } } } else { - field.checked = true + if (!field.disabled) { + field.checked = true; + } } } @@ -995,6 +1004,33 @@ sub select_language { =pod + +=item * &list_languages() + +Returns an array reference that is suitable for use in language prompters. +Each array element is itself a two element array. The first element +is the language code. The second element a descsriptiuon of the +language itself. This is suitable for use in e.g. +&Apache::edit::select_arg (once dereferenced that is). + +=cut + +sub list_languages { + my @lang_choices; + + foreach my $id (&languageids()) { + my $code = &supportedlanguagecode($id); + if ($code) { + my $selector = $supported_codes{$id}; + my $description = &plainlanguagedescription($id); + push (@lang_choices, [$selector, $description]); + } + } + return \@lang_choices; +} + +=pod + =item * &linked_select_forms(...) linked_select_forms returns a string containing a block @@ -2986,6 +3022,45 @@ sub get_related_words { untie %thesaurus_db; return @Words; } +############################################################### +# +# Spell checking +# + +=pod + +=head1 Spell checking + +=over 4 + +=item * &check_spelling($wordlist $language) + +Takes a string containing words and feeds it to an external +spellcheck program via a pipeline. Returns a string containing +them mis-spelled words. + +Parameters: + +=over 4 + +=item - $wordlist + +String that will be fed into the spellcheck program. + +=item - $language + +Language string that specifies the language for which the spell +check will be performed. + +=back + +=back + +Note: This sub assumes that aspell is installed. + + +=cut + =pod @@ -2993,6 +3068,31 @@ sub get_related_words { =cut +sub check_spelling { + my ($wordlist, $language) = @_; + my @misspellings; + + # Generate the speller and set the langauge. + # if explicitly selected: + + my $speller = Text::Aspell->new; + if ($language) { + $speller->set_option('lang', $language); + } + + # Turn the word list into an array of words by splittingon whitespace + + my @words = split(/\s+/, $wordlist); + + foreach my $word (@words) { + if(! $speller->check($word)) { + push(@misspellings, $word); + } + } + return join(' ', @misspellings); + +} + # -------------------------------------------------------------- Plaintext name =pod @@ -3226,7 +3326,7 @@ sub aboutmewrapper { if (!defined($username) && !defined($domain)) { return; } - return ''.$link.''; } @@ -4960,6 +5060,10 @@ Inputs: should it have jsmath forced on by the current page +=item * $advtoolsref, optional argument, ref to an array containing + inlineremote items to be added in "Functions" menu below + breadcrumbs. + =back Returns: A uniform header for LON-CAPA web pages. @@ -4971,7 +5075,7 @@ other decorations will be returned. sub bodytag { my ($title,$function,$addentries,$bodyonly,$domain,$forcereg, - $no_nav_bar,$bgcolor,$args)=@_; + $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_; my $public; if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')) @@ -5060,13 +5164,11 @@ sub bodytag { if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) { - unless ($env{'request.noversionuri'} =~ m{/res/adm/pages/bookmarkmenu/}) { - if ($dc_info) { - $dc_info = qq|$dc_info|; - } - $bodytag .= qq|
$name $role
- $realm $dc_info
|; - } + if ($dc_info) { + $dc_info = qq|$dc_info|; + } + $bodytag .= qq|
$name $role
+ $realm $dc_info
|; return $bodytag; } @@ -5092,8 +5194,15 @@ sub bodytag { if ($env{'request.state'} eq 'construct') { $bodytag .= &Apache::lonmenu::innerregister($forcereg, $args->{'bread_crumbs'}); - } elsif ($forcereg) { - $bodytag .= &Apache::lonmenu::innerregister($forcereg); + } elsif ($forcereg) { + $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef, + $args->{'group'}); + } else { + $bodytag .= + &Apache::lonmenu::prepare_functions($env{'request.noversionuri'}, + $forcereg,$args->{'group'}, + $args->{'bread_crumbs'}, + $advtoolsref); } }else{ # this is to seperate menu from content when there's no secondary @@ -5308,10 +5417,12 @@ form, .inline { .LC_error { color: red; - font-size: larger; } -.LC_warning, +.LC_warning { + color: darkorange; +} + .LC_diff_removed { color: red; } @@ -6554,52 +6665,15 @@ ul#LC_secondary_menu { margin: 0; width: 100%; text-align: left; - float: left; } ul#LC_secondary_menu li { font-weight: bold; line-height: 1.8em; - border-right: 1px solid black; - vertical-align: middle; - float: left; -} - -ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover { - background-color: $data_table_light; -} - -ul#LC_secondary_menu li a { padding: 0 0.8em; -} - -ul#LC_secondary_menu li ul { - display: none; -} - -ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul { - display: block; - position: absolute; - margin: 0; - padding: 0; - list-style:none; - float: none; - background-color: $data_table_light; - z-index: 2; -} - -ul#LC_secondary_menu li ul li { - font-size: 90%; - vertical-align: top; - border-left: 1px solid black; border-right: 1px solid black; - background-color: $data_table_light - list-style:none; - float: none; -} - -ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover { - background-color: $data_table_dark; + display: inline; + vertical-align: middle; } ul.LC_TabContent { @@ -6939,6 +7013,7 @@ ul#LC_toolbar { list-style:none; position:relative; background-color:white; + overflow: auto; } ul#LC_toolbar li { @@ -6948,6 +7023,7 @@ ul#LC_toolbar li { float: left; display:inline; vertical-align:middle; + white-space: nowrap; } @@ -7313,6 +7389,8 @@ $args - additional optional args support current page bread_crumbs -> Array containing breadcrumbs bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs + group -> includes the current group, if page is for a + specific group =back @@ -7325,7 +7403,7 @@ sub start_page { #&Apache::lonnet::logthis("start_page ".join(':',caller(0))); $env{'internal.start_page'}++; - my $result; + my ($result,@advtools); if (! exists($args->{'skip_phases'}{'head'}) ) { $result .= &xml_begin() . &headtag($title, $head_extra, $args); @@ -7342,7 +7420,8 @@ sub start_page { $args->{'function'}, $args->{'add_entries'}, $args->{'only_body'}, $args->{'domain'}, $args->{'force_register'}, $args->{'no_nav_bar'}, - $args->{'bgcolor'}, $args); + $args->{'bgcolor'}, $args, + \@advtools); } } @@ -7371,6 +7450,10 @@ sub start_page { &Apache::lonhtmlcommon::add_breadcrumb($crumb); } } + # if @advtools array contains items add then to the breadcrumbs + if (@advtools > 0) { + &Apache::lonmenu::advtools_crumbs(@advtools); + } #if bread_crumbs_component exists show it as headline else show only the breadcrumbs if(exists($args->{'bread_crumbs_component'})){ @@ -7766,7 +7849,7 @@ sub simple_error_page { my ($r,$title,$msg) = @_; my $page = &Apache::loncommon::start_page($title). - &mt($msg). + '

'.&mt($msg).'

'. &Apache::loncommon::end_page(); if (ref($r)) { $r->print($page); @@ -9353,7 +9436,7 @@ sub get_env_multiple { sub ask_for_embedded_content { my ($actionurl,$state,$allfiles,$codebase,$args)=@_; my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges, - %currsubfile,%unused); + %currsubfile,%unused,$rem); my $counter = 0; my $numnew = 0; my $numremref = 0; @@ -9366,6 +9449,10 @@ sub ask_for_embedded_content { my $heading = &mt('Upload embedded files'); my $buttontext = &mt('Upload'); + my $navmap; + if ($env{'request.course.id'}) { + $navmap = Apache::lonnavmaps::navmap->new(); + } if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { my $current_path='/'; if ($env{'form.currentpath'}) { @@ -9395,8 +9482,15 @@ sub ask_for_embedded_content { if (ref($args) eq 'HASH') { $url = $args->{'docs_url'}; $toplevel = $url; + if ($args->{'context'} eq 'paste') { + ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/}); + ($path) = + ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); + $fileloc = &Apache::lonnet::filelocation('',$toplevel); + $fileloc =~ s{^/}{}; + } } - } elsif ($actionurl eq '/adm/dependencies') { + } elsif ($actionurl eq '/adm/dependencies') { if ($env{'request.course.id'} ne '') { $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; @@ -9404,6 +9498,7 @@ sub ask_for_embedded_content { $url = $args->{'docs_url'}; $title = $args->{'docs_title'}; $toplevel = "/$url"; + ($rem) = ($toplevel =~ m{^(.+/)[^/]+$}); ($path) = ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); $fileloc = &Apache::lonnet::filelocation('',$toplevel); @@ -9466,7 +9561,9 @@ sub ask_for_embedded_content { my @subdir_list = grep(!/^\./,readdir($dir)); map {$currsubfile{$path}{$_} = 1;} @subdir_list; } - } elsif ($actionurl eq '/adm/dependencies') { + } elsif (($actionurl eq '/adm/dependencies') || + (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && + ($args->{'context'} eq 'paste'))) { if ($env{'request.course.id'} ne '') { my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$}); if ($dir ne '') { @@ -9502,6 +9599,12 @@ sub ask_for_embedded_content { if (ref($currsubfile{$path}) eq 'HASH') { foreach my $file (keys(%{$currsubfile{$path}})) { unless ($subdependencies{$path}{$file}) { + next if (($rem ne '') && + (($env{"httpref.$rem"."$path/$file"} ne '') || + (ref($navmap) && + (($navmap->getResourceByUrl($rem."$path/$file") ne '') || + (($file =~ /^(.*\.s?html?)\.bak$/i) && + ($navmap->getResourceByUrl($rem."$path/$1"))))))); $unused{$path.'/'.$file} = 1; } } @@ -9524,7 +9627,9 @@ sub ask_for_embedded_content { my @dir_list = grep(!/^\./,readdir($dir)); map {$currfile{$_} = 1;} @dir_list; } - } elsif ($actionurl eq '/adm/dependencies') { + } elsif (($actionurl eq '/adm/dependencies') || + (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && + ($args->{'context'} eq 'paste'))) { if ($env{'request.course.id'} ne '') { my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$}); if ($dir ne '') { @@ -9558,9 +9663,23 @@ sub ask_for_embedded_content { unless (($file eq $filename) || ($file eq $filename.'.bak') || ($dependencies{$file})) { + if ($actionurl eq '/adm/dependencies') { + next if (($rem ne '') && + (($env{"httpref.$rem".$file} ne '') || + (ref($navmap) && + (($navmap->getResourceByUrl($rem.$file) ne '') || + (($file =~ /^(.*\.s?html?)\.bak$/i) && + ($navmap->getResourceByUrl($rem.$1))))))); + } $unused{$file} = 1; } } + if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && + ($args->{'context'} eq 'paste')) { + $counter = scalar(keys(%existing)); + $numpathchg = scalar(keys(%pathchanges)); + return ($output,$counter,$numpathchg,\%existing); + } foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) { if ($actionurl eq '/adm/dependencies') { next if ($embed_file =~ m{^\w+://}); @@ -9577,7 +9696,6 @@ sub ask_for_embedded_content { $numremref++; } elsif ($args->{'error_on_invalid_names'} && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) { - $upload_output.=''.&mt('Invalid characters').''; $numinvalid++; } else { @@ -11065,7 +11183,10 @@ function dependencyCheck(form,count,offs document.getElementById('arc_depon_'+count).style.display='block'; form.elements[depitem].options.length = 0; form.elements[depitem].options[0] = new Option('Select','',true,true); - for (var i=1; i'."\n"; @@ -11289,7 +11411,7 @@ sub process_extracted_files { my ($outtext,$errtext)= &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'. $docuname.'/'.$folders{$outer}. - '.'.$containers{$outer},1); + '.'.$containers{$outer},1,1); unless ($errtext) { if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") { $result .= '
  • '.&mt('File: [_1] added to course',$docstitle).'
  • '."\n"; @@ -11297,84 +11419,90 @@ sub process_extracted_files { } } } - } elsif ($env{'form.archive_'.$i} eq 'dependency') { - my ($title) = ($path =~ m{/([^/]+)$}); - $referrer{$i} = $env{'form.archive_dependent_on_'.$i}; - if ($env{'form.archive_'.$referrer{$i}} eq 'display') { - if (ref($dirorder{$i}) eq 'ARRAY') { - my ($itemidx,$fullpath,$relpath); + } + } else { + $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'
    '; + } + } + for (my $i=1; $i<=$numitems; $i++) { + next unless ($env{'form.archive_'.$i} eq 'dependency'); + my $path = $env{'form.archive_content_'.$i}; + if ($path =~ /^\Q$pathtocheck\E/) { + my ($title) = ($path =~ m{/([^/]+)$}); + $referrer{$i} = $env{'form.archive_dependent_on_'.$i}; + if ($env{'form.archive_'.$referrer{$i}} eq 'display') { + if (ref($dirorder{$i}) eq 'ARRAY') { + my ($itemidx,$fullpath,$relpath); + if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') { + my $container = $dirorder{$referrer{$i}}->[-1]; for (my $j=0; $j<@{$dirorder{$i}}; $j++) { - if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') { - my $container = $dirorder{$referrer{$i}}->[-1]; - for (my $j=0; $j<@{$dirorder{$i}}; $j++) { - if ($dirorder{$i}->[$j] eq $container) { - $itemidx = $j; - } - } + if ($dirorder{$i}->[$j] eq $container) { + $itemidx = $j; } } - if ($itemidx ne '') { - if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) { - if ($mapinner{$referrer{$i}}) { - $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}"; - for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { - if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { - unless (defined($newseqid{$dirorder{$i}->[$j]})) { - $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; - $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; - if (!-e $fullpath) { - mkdir($fullpath,0755); - } - } - } else { - last; - } - } - } - } elsif ($newdest{$referrer{$i}}) { - $fullpath = $newdest{$referrer{$i}}; - for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { - if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') { - $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]}; - last; - } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { - unless (defined($newseqid{$dirorder{$i}->[$j]})) { - $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; - $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; - if (!-e $fullpath) { - mkdir($fullpath,0755); - } + } + if ($itemidx eq '') { + $itemidx = 0; + } + if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) { + if ($mapinner{$referrer{$i}}) { + $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}"; + for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { + if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { + unless (defined($newseqid{$dirorder{$i}->[$j]})) { + $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; + $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; + if (!-e $fullpath) { + mkdir($fullpath,0755); } - } else { - last; } + } else { + last; } } - if ($fullpath ne '') { - if (-e "$prefix$path") { - system("mv $prefix$path $fullpath/$title"); - } - if (-e "$fullpath/$title") { - my $showpath; - if ($relpath ne '') { - $showpath = "$relpath/$title"; - } else { - $showpath = "/$title"; - } - $result .= '
  • '.&mt('[_1] included as a dependency',$showpath).'
  • '."\n"; - } - unless ($ishome) { - my $fetch = "$fullpath/$title"; - $fetch =~ s/^\Q$prefix$dir\E//; - $prompttofetch{$fetch} = 1; + } + } elsif ($newdest{$referrer{$i}}) { + $fullpath = $newdest{$referrer{$i}}; + for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { + if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') { + $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]}; + last; + } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { + unless (defined($newseqid{$dirorder{$i}->[$j]})) { + $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; + $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; + if (!-e $fullpath) { + mkdir($fullpath,0755); + } } + } else { + last; } } } - } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') { - $warning .= &mt('[_1] is a dependency of [_2], which was discarded.', - $path,$env{'form.archive_content_'.$referrer{$i}}).'
    '; + if ($fullpath ne '') { + if (-e "$prefix$path") { + system("mv $prefix$path $fullpath/$title"); + } + if (-e "$fullpath/$title") { + my $showpath; + if ($relpath ne '') { + $showpath = "$relpath/$title"; + } else { + $showpath = "/$title"; + } + $result .= '
  • '.&mt('[_1] included as a dependency',$showpath).'
  • '."\n"; + } + unless ($ishome) { + my $fetch = "$fullpath/$title"; + $fetch =~ s/^\Q$prefix$dir\E//; + $prompttofetch{$fetch} = 1; + } + } } + } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') { + $warning .= &mt('[_1] is a dependency of [_2], which was discarded.', + $path,$env{'form.archive_content_'.$referrer{$i}}).'
    '; } } else { $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'
    '; @@ -13770,6 +13898,20 @@ sub init_user_environment { \%userenv,\%domdef,\%is_adv); } + $userenv{'canrequest.author'} = + &Apache::lonnet::usertools_access($username,$domain,'requestauthor', + 'reload','requestauthor', + \%userenv,\%domdef,\%is_adv); + my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'], + $domain,$username); + my $reqstatus = $reqauthor{'author_status'}; + if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { + if (ref($reqauthor{'author'}) eq 'HASH') { + $userenv{'requestauthorqueued'} = $reqstatus.':'. + $reqauthor{'author'}{'timestamp'}; + } + } + $env{'user.environment'} = "$lonids/$cookie.id"; if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id", @@ -13884,6 +14026,224 @@ sub build_release_hashes { return; } +sub update_content_constraints { + my ($cdom,$cnum,$chome,$cid) = @_; + my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired'); + my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'}); + my %checkresponsetypes; + foreach my $key (keys(%Apache::lonnet::needsrelease)) { + my ($item,$name,$value) = split(/:/,$key); + if ($item eq 'resourcetag') { + if ($name eq 'responsetype') { + $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key} + } + } + } + my $navmap = Apache::lonnavmaps::navmap->new(); + if (defined($navmap)) { + my %allresponses; + foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) { + my %responses = $res->responseTypes(); + foreach my $key (keys(%responses)) { + next unless(exists($checkresponsetypes{$key})); + $allresponses{$key} += $responses{$key}; + } + } + foreach my $key (keys(%allresponses)) { + my ($major,$minor) = split(/\./,$checkresponsetypes{$key}); + if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) { + ($reqdmajor,$reqdminor) = ($major,$minor); + } + } + undef($navmap); + } + unless (($reqdmajor eq '') && ($reqdminor eq '')) { + &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid); + } + return; +} + +sub parse_supplemental_title { + my ($title) = @_; + + my ($foldertitle,$renametitle); + if ($title =~ /&&&/) { + $title = &HTML::Entites::decode($title); + } + if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) { + $renametitle=$4; + my ($time,$uname,$udom) = ($1,$2,$3); + $foldertitle=&Apache::lontexconvert::msgtexconverted($4); + my $name = &plainname($uname,$udom); + $name = &HTML::Entities::encode($name,'"<>&\''); + $renametitle = &HTML::Entities::encode($renametitle,'"<>&\''); + $title=''.&Apache::lonlocal::locallocaltime($time).' '. + $name.':
    '.$foldertitle; + } + if (wantarray) { + return ($title,$foldertitle,$renametitle); + } + return $title; +} + +sub captcha_display { + my ($context,$lonhost) = @_; + my ($output,$error); + my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost); + if ($captcha eq 'original') { + $output = &create_captcha(); + unless ($output) { + $error = 'captcha'; + } + } elsif ($captcha eq 'recaptcha') { + $output = &create_recaptcha($pubkey); + unless ($output) { + $error = 'recaptcha'; + } + } + return ($output,$error); +} + +sub captcha_response { + my ($context,$lonhost) = @_; + my ($captcha_chk,$captcha_error); + my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost); + if ($captcha eq 'original') { + ($captcha_chk,$captcha_error) = &check_captcha(); + } elsif ($captcha eq 'recaptcha') { + $captcha_chk = &check_recaptcha($privkey); + } else { + $captcha_chk = 1; + } + return ($captcha_chk,$captcha_error); +} + +sub get_captcha_config { + my ($context,$lonhost) = @_; + my ($captcha,$pubkey,$privkey,$hashtocheck); + my $hostname = &Apache::lonnet::hostname($lonhost); + my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname); + my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID); + if ($context eq 'usercreation') { + my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom); + if (ref($domconfig{$context}) eq 'HASH') { + $hashtocheck = $domconfig{$context}{'cancreate'}; + if (ref($hashtocheck) eq 'HASH') { + if ($hashtocheck->{'captcha'} eq 'recaptcha') { + if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') { + $pubkey = $hashtocheck->{'recaptchakeys'}{'public'}; + $privkey = $hashtocheck->{'recaptchakeys'}{'private'}; + } + if ($privkey && $pubkey) { + $captcha = 'recaptcha'; + } else { + $captcha = 'original'; + } + } elsif ($hashtocheck->{'captcha'} ne 'notused') { + $captcha = 'original'; + } + } + } else { + $captcha = 'captcha'; + } + } elsif ($context eq 'login') { + my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom); + if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') { + $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'}; + $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'}; + if ($privkey && $pubkey) { + $captcha = 'recaptcha'; + } else { + $captcha = 'original'; + } + } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') { + $captcha = 'original'; + } + } + return ($captcha,$pubkey,$privkey); +} + +sub create_captcha { + my %captcha_params = &captcha_settings(); + my ($output,$maxtries,$tries) = ('',10,0); + while ($tries < $maxtries) { + $tries ++; + my $captcha = Authen::Captcha->new ( + output_folder => $captcha_params{'output_dir'}, + data_folder => $captcha_params{'db_dir'}, + ); + my $md5sum = $captcha->generate_code($captcha_params{'numchars'}); + + if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') { + $output = ''."\n". + &mt('Type in the letters/numbers shown below').' '. + '
    '. + ''; + last; + } + } + return $output; +} + +sub captcha_settings { + my %captcha_params = ( + output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'}, + www_output_dir => "/captchaspool", + db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'}, + numchars => '5', + ); + return %captcha_params; +} + +sub check_captcha { + my ($captcha_chk,$captcha_error); + my $code = $env{'form.code'}; + my $md5sum = $env{'form.crypt'}; + my %captcha_params = &captcha_settings(); + my $captcha = Authen::Captcha->new( + output_folder => $captcha_params{'output_dir'}, + data_folder => $captcha_params{'db_dir'}, + ); + my $captcha_chk = $captcha->check_code($code,$md5sum); + my %captcha_hash = ( + 0 => 'Code not checked (file error)', + -1 => 'Failed: code expired', + -2 => 'Failed: invalid code (not in database)', + -3 => 'Failed: invalid code (code does not match crypt)', + ); + if ($captcha_chk != 1) { + $captcha_error = $captcha_hash{$captcha_chk} + } + return ($captcha_chk,$captcha_error); +} + +sub create_recaptcha { + my ($pubkey) = @_; + my $captcha = Captcha::reCAPTCHA->new; + return $captcha->get_options_setter({theme => 'white'})."\n". + $captcha->get_html($pubkey). + &mt('If either word is hard to read, [_1] will replace them.', + 'reCAPTCHA refresh'). + '

    '; +} + +sub check_recaptcha { + my ($privkey) = @_; + my $captcha_chk; + my $captcha = Captcha::reCAPTCHA->new; + my $captcha_result = + $captcha->check_answer( + $privkey, + $ENV{'REMOTE_ADDR'}, + $env{'form.recaptcha_challenge_field'}, + $env{'form.recaptcha_response_field'}, + ); + if ($captcha_result->{is_valid}) { + $captcha_chk = 1; + } + return $captcha_chk; +} + =pod =back