--- loncom/interface/loncommon.pm 2009/02/13 17:26:55 1.746 +++ loncom/interface/loncommon.pm 2016/08/25 22:33:02 1.1251 @@ -1,7 +1,7 @@ # The LearningOnline Network with CAPA # a pile of common routines # -# $Id: loncommon.pm,v 1.746 2009/02/13 17:26:55 neumanie Exp $ +# $Id: loncommon.pm,v 1.1251 2016/08/25 22:33:02 raeburn Exp $ # # Copyright Michigan State University Board of Trustees # @@ -67,9 +67,22 @@ use Apache::lonhtmlcommon(); use Apache::loncoursedata(); 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 DateTime::Locale; +use Encode(); +use Text::Aspell; +use Authen::Captcha; +use Captcha::reCAPTCHA; +use JSON::DWIW; +use LWP::UserAgent; +use Crypt::DES; +use DynaLoader; # for Crypt::DES version +use MIME::Lite; +use MIME::Types; # ---------------------------------------------- Designs use vars qw(%defaultdesign); @@ -154,6 +167,9 @@ 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; my %scprtag; my %fe; my %fd; my %fm; @@ -186,11 +202,16 @@ BEGIN { while (my $line = <$fh>) { next if ($line=~/^\#/); chomp($line); - my ($key,$two,$country,$three,$enc,$val,$sup)=(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{$code} = $latex; + } } close($fh); } @@ -406,9 +427,10 @@ sub studentbrowser_javascript { || ($env{'request.role'}=~/^(au|dc|su)/) ) { return ''; } return (<<'ENDSTDBRW'); - ENDSTDBRW } +sub resourcebrowser_javascript { + unless ($env{'request.course.id'}) { return ''; } + return (<<'ENDRESBRW'); + +ENDRESBRW +} + sub selectstudent_link { - my ($form,$unameele,$udomele)=@_; + my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_; + my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','". + &Apache::lonhtmlcommon::entity_encode($unameele)."','". + &Apache::lonhtmlcommon::entity_encode($udomele)."'"; if ($env{'request.course.id'}) { if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'}) && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}. '/'.$env{'request.course.sec'})) { return ''; } - return "".&mt('Select User').""; + $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'"; + if ($courseadvonly) { + $callargs .= ",'',1,1"; + } + return ''. + ''. + &mt('Select User').''; } if ($env{'request.role'}=~/^(au|dc|su)/) { - return "".&mt('Select User').""; + $callargs .= ",'',1"; + return ''. + ''. + &mt('Select User').''; } return ''; } +sub selectresource_link { + my ($form,$reslink,$arg)=@_; + + my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','". + &Apache::lonhtmlcommon::entity_encode($reslink)."'"; + unless ($env{'request.course.id'}) { return $arg; } + return ''. + ''. + $arg.''; +} + + + sub authorbrowser_javascript { return <<"ENDAUTHORBRW"; - ENDAUTHORBRW } sub coursebrowser_javascript { - my ($domainfilter,$sec_element,$formname)=@_; - my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role'); - my $output = ' -'; + return $output; +} + +sub javascript_index_functions { + return <<"ENDJS"; + +function getFormIdByName(formname) { + for (var i=0;i -1) { + var domid = getIndexByName(formid,udom); + if (domid > -1) { + if (document.forms[formid].elements[domid].type == 'select-one') { + userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value; + } + if (document.forms[formid].elements[domid].type == 'hidden') { + userdom=document.forms[formid].elements[domid].value; } } - return -1; } + return userdom; +} - function getIndexByName(formid,item) { - for (var i=0;i +// >> 0; + if (len === 0) { + return -1; + } + var n = 0; + if (arguments.length > 0) { + n = Number(arguments[1]); + 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)); + } + } + if (n >= len) { + return -1; + } + var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); + for (; k < len; k++) { + if (k in t && t[k] === searchElement) { + return k; } } return -1; } -ENDSTDBRW - if ($sec_element ne '') { - $output .= &setsec_javascript($sec_element,$formname); +} + +// ]]> + + +ENDJS + +} + +sub userbrowser_javascript { + my $id_functions = &javascript_index_functions(); + return <<"ENDUSERBRW"; + +function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) { + var url = '/adm/pickuser?'; + var userdom = getDomainFromSelectbox(formname,udom); + if (userdom != null) { + if (userdom != '') { + url += 'srchdom='+userdom+'&'; + } } - $output .= ' -'; - return $output; + url += 'form=' + formname + '&unameelement='+uname+ + '&udomelement='+udom+ + '&ulastelement='+ulast+ + '&ufirstelement='+ufirst+ + '&uemailelement='+uemail+ + '&hideudomelement='+hideudom+ + '&coursedom='+crsdom; + if ((caller != null) && (caller != undefined)) { + url += '&caller='+caller; + } + var title = 'User_Browser'; + var options = 'scrollbars=1,resizable=1,menubar=0'; + options += ',width=700,height=600'; + var stdeditbrowser = open(url,title,options,'1'); + stdeditbrowser.focus(); +} + +function fix_domain (formname,udom,origdom,uname) { + var formid = getFormIdByName(formname); + if (formid > -1) { + var unameid = getIndexByName(formid,uname); + var domid = getIndexByName(formid,udom); + var hidedomid = getIndexByName(formid,origdom); + if (hidedomid > -1) { + var fixeddom = document.forms[formid].elements[hidedomid].value; + var unameval = document.forms[formid].elements[unameid].value; + if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) { + if (domid > -1) { + var slct = document.forms[formid].elements[domid]; + if (slct.type == 'select-one') { + var i; + for (i=0;i".&mt('Select Course').""; + my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype, + $typeelement) = @_; + my $type = $selecttype; + my $linktext = &mt('Select Course'); + if ($selecttype eq 'Community') { + $linktext = &mt('Select Community'); + } elsif ($selecttype eq 'Placement') { + $linktext = &mt('Select Placement Test'); + } elsif ($selecttype eq 'Course/Community') { + $linktext = &mt('Select Course/Community'); + $type = ''; + } elsif ($selecttype eq 'Select') { + $linktext = &mt('Select'); + $type = ''; + } + return '' + ."".$linktext.'' + .''; } sub selectauthor_link { @@ -612,15 +905,27 @@ sub selectauthor_link { &mt('Select Author').''; } +sub selectuser_link { + my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem, + $coursedom,$linktext,$caller) = @_; + return ''.$linktext.''; +} + sub check_uncheck_jscript { my $jscript = <<"ENDSCRT"; 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; + } } } @@ -669,15 +974,16 @@ sub select_datelocale { } $output .= '> '; } + my @languages = &Apache::lonlocal::preferred_languages(); my (@possibles,%locale_names); - my @locales = DateTime::Locale::Catalog::Locales; - foreach my $locale (@locales) { - if (ref($locale) eq 'HASH') { - my $id = $locale->{'id'}; - if ($id ne '') { - my $en_terr = $locale->{'en_territory'}; - my $native_terr = $locale->{'native_territory'}; - my @languages = &Apache::lonlocal::preferred_languages(); + my @locales = DateTime::Locale->ids(); + foreach my $id (@locales) { + if ($id ne '') { + my ($en_terr,$native_terr); + my $loc = DateTime::Locale->load($id); + if (ref($loc)) { + $en_terr = $loc->name(); + $native_terr = $loc->native_name(); if (grep(/^en$/,@languages) || !@languages) { if ($en_terr ne '') { $locale_names{$id} = '('.$en_terr.')'; @@ -691,8 +997,9 @@ sub select_datelocale { $locale_names{$id} = '('.$en_terr.')'; } } - push (@possibles,$id); - } + $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id}); + push(@possibles,$id); + } } } foreach my $item (sort(@possibles)) { @@ -702,7 +1009,7 @@ sub select_datelocale { } $output.=">$item"; if ($locale_names{$item} ne '') { - $output.=" $locale_names{$item}\n"; + $output.=' '.$locale_names{$item}; } $output.="\n"; } @@ -710,6 +1017,49 @@ sub select_datelocale { return $output; } +sub select_language { + my ($name,$selected,$includeempty) = @_; + my %langchoices; + if ($includeempty) { + %langchoices = ('' => 'No language preference'); + } + foreach my $id (&languageids()) { + my $code = &supportedlanguagecode($id); + if ($code) { + $langchoices{$code} = &plainlanguagedescription($id); + } + } + %langchoices = &Apache::lonlocal::texthash(%langchoices); + return &select_form($selected,$name,\%langchoices); +} + +=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(...) @@ -738,6 +1088,15 @@ linked_select_forms takes the following =item * $menuorder, the order of values in the first menu +=item * $onchangefirst, additional javascript call to execute for an onchange + event for the first tag + +=item * $suffix, to differentiate separate uses of select2data javascript + objects in a page. + =back Below is an example of such a hash. Only the 'text', 'default', and @@ -791,26 +1150,30 @@ sub linked_select_forms { $secondselectname, $hashref, $menuorder, + $onchangefirst, + $onchangesecond, + $suffix ) = @_; my $second = "document.$formname.$secondselectname"; my $first = "document.$formname.$firstselectname"; # output the javascript to do the changing my $result = ''; - $result.=" END # output the initial values for the selection lists - $result .= "\n"; my @order = sort(keys(%{$hashref})); if (ref($menuorder) eq 'ARRAY') { @order = @{$menuorder}; @@ -858,7 +1220,11 @@ END $result .= "\n"; my %select2 = %{$hashref->{$firstdefault}->{'select2'}}; $result .= $middletext; - $result .= "{$firstdefault}->{'default'}; my @secondorder = sort(keys(%select2)); @@ -877,7 +1243,7 @@ END =pod -=item * &help_open_topic($topic,$text,$stayOnPage,$width,$height) +=item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid) Returns a string corresponding to an HTML link to the given help $topic, where $topic corresponds to the name of a .tex file in @@ -895,18 +1261,19 @@ a new window using Javascript. (Default $width and $height are optional numerical parameters that will override the width and height of the popped up window, which may -be useful for certain help topics with big pictures included. +be useful for certain help topics with big pictures included. + +$imgid is the id of the img tag used for the help icon. This may be +used in a javascript call to switch the image src. See +lonhtmlcommon::htmlareaselectactive() for an example. =cut sub help_open_topic { - my ($topic, $text, $stayOnPage, $width, $height) = @_; + my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_; $text = "" if (not defined $text); $stayOnPage = 0 if (not defined $stayOnPage); - if ($env{'browser.interface'} eq 'textual') { - $stayOnPage=1; - } - $width = 350 if (not defined $width); + $width = 500 if (not defined $width); $height = 400 if (not defined $height); my $filename = $topic; $filename =~ s/ /_/g; @@ -917,25 +1284,34 @@ sub help_open_topic { $topic=~s/\W/\_/g; if (!$stayOnPage) { - $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; + $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');"; + } elsif ($stayOnPage eq 'popup') { + $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; } else { $link = "/adm/help/${filename}.hlp"; } # Add the text - if ($text ne "") { - $template .= - "". - "
$text"; + if ($text ne "") { + $template.='' + .'' + .$text.''; } - # Add the graphic + # (Always) Add the graphic my $title = &mt('Online Help'); my $helpicon=&lonhttpdurl("/adm/help/help.png"); - $template .= <<"ENDTEMPLATE"; - (Help: $topic) -ENDTEMPLATE - if ($text ne '') { $template.='
' }; + if ($imgid ne '') { + $imgid = ' id="'.$imgid.'"'; + } + $template.=' ' + .''.&mt('Help: [_1]',$topic).''; + if ($text ne "") { + $template.=''; + } return $template; } @@ -943,29 +1319,27 @@ ENDTEMPLATE # This is a quicky function for Latex cheatsheet editing, since it # appears in at least four places sub helpLatexCheatsheet { - my ($topic,$text,$not_author) = @_; + my ($topic,$text,$not_author,$stayOnPage) = @_; my $out; my $addOther = ''; if ($topic) { - $addOther = &Apache::loncommon::help_open_topic($topic,$text, - undef, undef, 600). - ''; - } - $out = ''; + $addOther = ''.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).' '; + } + $out = '' # Start cheatsheet + .$addOther + .'' + .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600) + .' ' + .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600) + .''; unless ($not_author) { - $out .= ''; + $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 .= '
'. - $addOther . - &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'), - undef,undef,600). - ''. - &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'), - undef,undef,600). - ''. - &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'), - undef,undef,600). - '
'; + $out .= ''; # End cheatsheet return $out; } @@ -973,7 +1347,7 @@ sub general_help { my $helptopic='Student_Intro'; if ($env{'request.role'}=~/^(ca|au)/) { $helptopic='Authoring_Intro'; - } elsif ($env{'request.role'}=~/^cc/) { + } elsif ($env{'request.role'}=~/^(cc|co)/) { $helptopic='Course_Coordination_Intro'; } elsif ($env{'request.role'}=~/^dc/) { $helptopic='Domain_Coordination_Intro'; @@ -993,7 +1367,9 @@ sub update_help_link { my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage"; my $output .= <<"ENDOUTPUT"; ENDOUTPUT return $output; @@ -1003,13 +1379,7 @@ ENDOUTPUT sub help_open_menu { my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) = @_; - $stayOnPage = 0 if (not defined $stayOnPage); - # only use pop-up help (stayOnPage == 0) - # if environment.remote is on (using remote control UI) - if ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ) { - $stayOnPage=1; - } + $stayOnPage = 1; my $output; if ($component_help) { if (!$text) { @@ -1030,39 +1400,40 @@ sub help_open_menu { sub top_nav_help { my ($text) = @_; $text = &mt($text); - my $stay_on_page = - ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ); - 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 $stay_on_page = 1; + 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 $stayOnPage = - ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ); - + 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, @@ -1070,8 +1441,8 @@ sub help_menu_js { my $template .= <<"ENDTEMPLATE"; ENDTEMPLATE return $template; @@ -1108,11 +1480,7 @@ sub help_open_bug { unless ($env{'user.adv'}) { return ''; } unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; } $text = "" if (not defined $text); - $stayOnPage = 0 if (not defined $stayOnPage); - if ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ) { $stayOnPage=1; - } $width = 600 if (not defined $width); $height = 600 if (not defined $height); @@ -1153,11 +1521,7 @@ sub help_open_faq { unless ($env{'user.adv'}) { return ''; } unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; } $text = "" if (not defined $text); - $stayOnPage = 0 if (not defined $stayOnPage); - if ($env{'browser.interface'} eq 'textual' || - $env{'environment.remote'} eq 'off' ) { $stayOnPage=1; - } $width = 350 if (not defined $width); $height = 400 if (not defined $height); @@ -1365,6 +1729,7 @@ sub resize_textarea_js { my $geometry = &viewport_geometry_js(); return <<"RESIZE"; RESIZE } +sub colorfuleditor_js { + my $browse_or_search; + my $respath; + my ($cnum,$cdom) = &crsauthor_url(); + if ($cnum) { + $respath = "/res/$cdom/$cnum/"; + my %js_lt = &Apache::lonlocal::texthash( + sunm => 'Sub-directory name', + save => 'Save page to make this permanent', + ); + &js_escape(\%js_lt); + $browse_or_search = <<"END"; + + function toggleChooser(form,element,titleid,only,search) { + var disp = 'none'; + if (document.getElementById('chooser_'+element)) { + var curr = document.getElementById('chooser_'+element).style.display; + if (curr == 'none') { + disp='inline'; + if (form.elements['chooser_'+element].length) { + for (var i=0; i 1) { + window['select1'+element+'_changed'](); + } + } + } + document.getElementById('chooser_'+element+'_crsres').style.display = 'block'; + + } + if (document.getElementById('chooser_'+element+'_upload')) { + document.getElementById('chooser_'+element+'_upload').style.display = 'none'; + if (document.getElementById('uploadcrsres_'+element)) { + document.getElementById('uploadcrsres_'+element).value = ''; + } + } + return; + } + + function toggleCrsUpload(form,element,numcrsdirs) { + if (document.getElementById('chooser_'+element+'_crsres')) { + document.getElementById('chooser_'+element+'_crsres').style.display = 'none'; + } + if (document.getElementById('chooser_'+element+'_upload')) { + var curr = document.getElementById('chooser_'+element+'_upload').style.display; + if (curr == 'none') { + if (numcrsdirs) { + form.elements['crsauthorpath_'+element].selectedIndex = 0; + form.elements['newsubdir_'+element][0].checked = true; + toggleNewsubdir(form,element); + } + } + document.getElementById('chooser_'+element+'_upload').style.display = 'block'; + } + return; + } + + function toggleResImport(form,element) { + var choices = new Array('crsres','upload'); + for (var i=0; i +// + function fold_box(curDepth, lastresource){ + + // we need a list because there can be several blocks you need to fold in one tag + var block = document.getElementsByName('foldblock_'+curDepth); + // but there is only one folding button per tag + var foldbutton = document.getElementById('folding_btn_'+curDepth); + + if(block.item(0).style.display == 'none'){ + + foldbutton.value = '@{[&mt("Hide")]}'; + for (i = 0; i < block.length; i++){ + block.item(i).style.display = ''; + } + }else{ + + foldbutton.value = '@{[&mt("Show")]}'; + for (i = 0; i < block.length; i++){ + // block.item(i).style.visibility = 'collapse'; + block.item(i).style.display = 'none'; + } + }; + saveState(lastresource); + } + + function saveState (lastresource) { + + var tag_list = getTagList(); + if(tag_list != null){ + var timestamp = new Date().getTime(); + var key = lastresource; + + // the value pattern is: 'time;key1,value1;key2,value2; ... ' + // starting with timestamp + var value = timestamp+';'; + + // building the list of key-value pairs + for(var i = 0; i < tag_list.length; i++){ + value += tag_list[i]+','; + value += document.getElementsByName(tag_list[i])[0].style.display+';'; + } + + // only iterate whole storage if nothing to override + if(localStorage.getItem(key) == null){ + + // prevent storage from growing large + if(localStorage.length > 50){ + var regex_getTimestamp = /^(?:\d)+;/; + var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0)); + var oldest_key; + + for(var i = 1; i < localStorage.length; i++){ + if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) { + oldest_key = localStorage.key(i); + oldest_timestamp = regex_getTimestamp.exec(oldest_key); + } + } + localStorage.removeItem(oldest_key); + } + } + localStorage.setItem(key,value); + } + } + + // restore folding status of blocks (on page load) + function restoreState (lastresource) { + if(localStorage.getItem(lastresource) != null){ + var key = lastresource; + var value = localStorage.getItem(key); + var regex_delTimestamp = /^\d+;/; + + value.replace(regex_delTimestamp, ''); + + var valueArr = value.split(';'); + var pairs; + var elements; + for (var i = 0; i < valueArr.length; i++){ + pairs = valueArr[i].split(','); + elements = document.getElementsByName(pairs[0]); + + for (var j = 0; j < elements.length; j++){ + elements[j].style.display = pairs[1]; + if (pairs[1] == "none"){ + var regex_id = /([_\\d]+)\$/; + regex_id.exec(pairs[0]); + document.getElementById("folding_btn"+RegExp.\$1).value = "Show"; + } + } + } + } + } + + function getTagList () { + + var stringToSearch = document.lonhomework.innerHTML; + + var ret = new Array(); + var regex_findBlock = /(foldblock_.*?)"/g; + var tag_list = stringToSearch.match(regex_findBlock); + + if(tag_list != null){ + for(var i = 0; i < tag_list.length; i++){ + ret.push(tag_list[i].replace(/"/, '')); + } + } + return ret; + } + + function saveScrollPosition (resource) { + var tag_list = getTagList(); + + // we dont always want to jump to the first block + // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this + if(\$(window).scrollTop() > 170){ + if(tag_list != null){ + var result; + for(var i = 0; i < tag_list.length; i++){ + if(isElementInViewport(tag_list[i])){ + result += tag_list[i]+';'; + } + } + sessionStorage.setItem('anchor_'+resource, result); + } + } else { + // we dont need to save zero, just delete the item to leave everything tidy + sessionStorage.removeItem('anchor_'+resource); + } + } + + function restoreScrollPosition(resource){ + + var elem = sessionStorage.getItem('anchor_'+resource); + if(elem != null){ + var tag_list = elem.split(';'); + var elem_list; + + for(var i = 0; i < tag_list.length; i++){ + elem_list = document.getElementsByName(tag_list[i]); + + if(elem_list.length > 0){ + elem = elem_list[0]; + break; + } + } + elem.scrollIntoView(); + } + } + + function isElementInViewport(el) { + + // change to last element instead of first + var elem = document.getElementsByName(el); + var rect = elem[0].getBoundingClientRect(); + + return ( + rect.top >= 0 && + rect.left >= 0 && + rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */ + rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ + ); + } + + function autosize(depth){ + var cmInst = window['cm'+depth]; + var fitsizeButton = document.getElementById('fitsize'+depth); + + // is fixed size, switching to dynamic + if (sessionStorage.getItem("autosized_"+depth) == null) { + cmInst.setSize("","auto"); + fitsizeButton.value = "@{[&mt('Fixed size')]}"; + sessionStorage.setItem("autosized_"+depth, "yes"); + + // is dynamic size, switching to fixed + } else { + cmInst.setSize("","300px"); + fitsizeButton.value = "@{[&mt('Dynamic size')]}"; + sessionStorage.removeItem("autosized_"+depth); + } + } + +$browse_or_search + +// ]]> + +COLORFULEDIT +} + +sub xmleditor_js { + return < + +XMLEDIT +} + +sub insert_folding_button { + my $curDepth = $Apache::lonxml::curdepth; + my $lastresource = $env{'request.ambiguous'}; + + return ""; +} + +sub crsauthor_url { + my ($url) = @_; + if ($url eq '') { + $url = $ENV{'REQUEST_URI'}; + } + my ($cnum,$cdom); + if ($env{'request.course.id'}) { + my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/}); + if ($audom ne '' && $auname ne '') { + if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) && + ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) { + $cnum = $auname; + $cdom = $audom; + } + } + } + return ($cnum,$cdom); +} + +sub import_crsauthor_form { + my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix) = @_; + return (0) unless ($env{'request.course.id'}); + my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; + my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; + my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'}; + return (0) unless (($cnum ne '') && ($cdom ne '')); + my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'}; + my @ids=&Apache::lonnet::current_machine_ids(); + my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus); + + if (grep(/^\Q$crshome\E$/,@ids)) { + $is_home = 1; + } + $relpath = "/priv/$cdom/$cnum"; + &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files); + my %lt = &Apache::lonlocal::texthash ( + fnam => 'Filename', + dire => 'Directory', + ); + my $numdirs = scalar(keys(%files)); + my (%possexts,$singledir,@singledirfiles); + if ($only) { + map { $possexts{$_} = 1; } split(/\s*,\s*/,$only); + } + my (%nonemptydirs,$possdirs); + if ($numdirs > 1) { + my @order; + foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) { + if (ref($files{$key}) eq 'HASH') { + my $shown = $key; + if ($key eq '') { + $shown = '/'; + } + my @ordered = (); + foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) { + if ($only) { + my ($ext) = ($file =~ /\.([^.]+)$/); + unless ($possexts{lc($ext)}) { + next; + } + } + $selimport_menus{$key}->{'select2'}->{$file} = $file; + push(@ordered,$file); + } + if (@ordered) { + push(@order,$key); + $nonemptydirs{$key} = 1; + $selimport_menus{$key}->{'text'} = $shown; + $selimport_menus{$key}->{'default'} = ''; + $selimport_menus{$key}->{'select2'}->{''} = ''; + $selimport_menus{$key}->{'order'} = \@ordered; + } + } + } + $possdirs = scalar(keys(%nonemptydirs)); + if ($possdirs > 1) { + my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs)); + $output = $lt{'dire'}. + &linked_select_forms($form,'
'. + $lt{'fnam'},'', + $firstselectname,$secondselectname, + \%selimport_menus,\@order, + $onchangefirst,'',$suffix).'
'; + } elsif ($possdirs == 1) { + $singledir = (keys(%nonemptydirs))[0]; + if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') { + @singledirfiles = @{$selimport_menus{$singledir}->{'order'}}; + } + delete($selimport_menus{$singledir}); + } + } elsif ($numdirs == 1) { + $singledir = (keys(%files))[0]; + foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) { + if ($only) { + my ($ext) = ($file =~ /\.([^.]+)$/); + unless ($possexts{lc($ext)}) { + next; + } + } + push(@singledirfiles,$file); + } + if (@singledirfiles) { + $possdirs == 1; + } + } + if (($possdirs == 1) && (@singledirfiles)) { + my $showdir = $singledir; + if ($singledir eq '') { + $showdir = '/'; + } + $output = $lt{'dire'}. + '
'. + $lt{'fnam'}.'
'."\n"; + } + return ($possdirs,$output); +} + =pod =head1 Excel and CSV file utility routines -=over 4 - =cut ############################################################### @@ -1421,6 +2300,8 @@ RESIZE =pod +=over 4 + =item * &csv_translate($text) Translate $text to allow it to be output as a 'comma separated values' @@ -1472,6 +2353,7 @@ Inputs: $workbook Returns: $format, a hash reference. + =cut ############################################################### @@ -1523,14 +2405,17 @@ sub create_workbook { my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename); if (! defined($workbook)) { $r->log_error("Error creating excel spreadsheet $filename: $!"); - $r->print('

'.&mt("Unable to create new Excel file. ". - "This error has been logged. ". - "Please alert your LON-CAPA administrator"). - '

'); + $r->print( + '

' + .&mt('Problems occurred in creating the new Excel file.') + .' '.&mt('This error has been logged.') + .' '.&mt('Please alert your LON-CAPA administrator.') + .'

' + ); return (undef); } # - $workbook->set_tempdir('/home/httpd/perl/tmp'); + $workbook->set_tempdir(LONCAPA::tempdir()); # my $format = &Apache::loncommon::define_excel_formats($workbook); return ($workbook,$filename,$format); @@ -1566,9 +2451,13 @@ sub create_text_file { $fh = Apache::File->new('>/home/httpd'.$filename); if (! defined($fh)) { $r->log_error("Couldn't open $filename for output $!"); - $r->print(&mt('Problems occurred in creating the output file. ' - .'This error has been logged. ' - .'Please alert your LON-CAPA administrator.')); + $r->print( + '

' + .&mt('Problems occurred in creating the output file.') + .' '.&mt('This error has been logged.') + .' '.&mt('Please alert your LON-CAPA administrator.') + .'

' + ); } return ($fh,$filename) } @@ -1597,7 +2486,7 @@ sub domain_select { return &multiple_select_form($name,$value,4,\%domains); } else { $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))]; - return &select_form($name,$value,%domains); + return &select_form($name,$value,\%domains); } } @@ -1659,29 +2548,40 @@ sub multiple_select_form { =pod -=item * &select_form($defdom,$name,%hash) +=item * &select_form($defdom,$name,$hashref,$onchange) Returns a string containing a \n"; + my ($def,$name,$hashref,$onchange,$readonly) = @_; + return unless (ref($hashref) eq 'HASH'); + if ($onchange) { + $onchange = ' onchange="'.$onchange.'"'; + } + my $disabled; + if ($readonly) { + $disabled = ' disabled="disabled"'; + } + my $selectform = ""; return $selectform; @@ -1690,19 +2590,112 @@ sub select_form { # For display filters sub display_filter { + my ($context) = @_; if (!$env{'form.show'}) { $env{'form.show'}=10; } if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; } - return '