--- loncom/interface/lonhtmlcommon.pm 2006/04/18 22:35:41 1.124 +++ loncom/interface/lonhtmlcommon.pm 2010/01/26 13:08:08 1.265 @@ -1,7 +1,7 @@ # The LearningOnline Network with CAPA # a pile of common html routines # -# $Id: lonhtmlcommon.pm,v 1.124 2006/04/18 22:35:41 albertel Exp $ +# $Id: lonhtmlcommon.pm,v 1.265 2010/01/26 13:08:08 wenzelju Exp $ # # Copyright Michigan State University Board of Trustees # @@ -60,6 +60,101 @@ use Time::Local; use Time::HiRes; use Apache::lonlocal; use Apache::lonnet; +use LONCAPA; + + +sub coursepreflink { + my ($text,$category)=@_; + if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) { + return '&"').'">'.$text.''; + } else { + return ''; + } +} + +sub raw_href_to_link { + my ($message)=@_; + $message=~s/(https?\:\/\/[^\s\'\"\<]+)([\s\<]|$)/$1<\/tt><\/a>$2/gi; + return $message; +} + +############################################## +############################################## + +=item confirm_success + +Successful completion of an operation message + +=cut + +sub confirm_success { + my ($message,$failure)=@_; + if ($failure) { + return ''."\n" + .''.&mt('Error').' '."\n" + .$message."\n" + .''."\n"; + } else { + return ''."\n" + .''.&mt('OK').' '."\n" + .$message."\n" + .''."\n"; + } +} + +############################################## +############################################## + +=pod + +=item dragmath_button + +Creates a button that launches a dragmath popup-window, in which an +expression can be edited and pasted as LaTeX into a specified textarea. + + textarea - Name of the textarea to edit. + helpicon - If true, show a help icon to the right of the button. + +=cut + +sub dragmath_button { + my ($textarea,$helpicon) = @_; + my $help_text; + if ($helpicon) { + $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor'); + } + my $buttontext=&mt('Edit Math'); + return <$help_text +ENDDRAGMATH +} + +############################################## + +=pod + +=item dragmath_js + +Javascript used to open pop-up window containing dragmath applet which +can be used to paste LaTeX into a textarea. +=cut + +sub dragmath_js { + my ($popup) = @_; + return < + // + + +ENDDRAGMATHJS +} + ############################################## ############################################## @@ -76,12 +171,12 @@ use Apache::lonnet; sub authorbombs { my $url=shift; $url=&Apache::lonnet::declutter($url); - my ($udom,$uname)=($url=~/^(\w+)\/(\w+)\//); + my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/}); my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom); - foreach (keys %bombs) { - if ($_=~/^$udom\/$uname\//) { + foreach my $bomb (keys(%bombs)) { + if ($bomb =~ /^$udom\/$uname\//) { return ''. + '">'.&mt('Bomb').''. &Apache::loncommon::help_open_topic('About_Bombs'); } } @@ -93,29 +188,35 @@ sub authorbombs { sub recent_filename { my $area=shift; - return 'nohist_recent_'.&Apache::lonnet::escape($area); + return 'nohist_recent_'.&escape($area); } sub store_recent { - my ($area,$name,$value)=@_; + my ($area,$name,$value,$freeze)=@_; my $file=&recent_filename($area); my %recent=&Apache::lonnet::dump($file); if (scalar(keys(%recent))>20) { # remove oldest value - my $oldest=time; + my $oldest=time(); my $delkey=''; - foreach (keys %recent) { - my $thistime=(split(/\&/,$recent{$_}))[0]; - if ($thistime<$oldest) { + foreach my $item (keys(%recent)) { + my $thistime=(split(/\&/,$recent{$item}))[0]; + if (($thistime ne "always_include") && ($thistime<$oldest)) { $oldest=$thistime; - $delkey=$_; + $delkey=$item; } } &Apache::lonnet::del($file,[$delkey]); } # store new value + my $timestamp; + if ($freeze) { + $timestamp = "always_include"; + } else { + $timestamp = time(); + } &Apache::lonnet::put($file,{ $name => - time.'&'.&Apache::lonnet::escape($value) }); + $timestamp.'&'.&escape($value) }); } sub remove_recent { @@ -130,11 +231,15 @@ sub select_recent { my $return="\n'; return $Str; @@ -201,7 +328,7 @@ sub checkbox { $Str .= 'value="'.$value.'"'; } if ($checked) { - $Str .= ' checked="1"'; + $Str .= ' checked="checked"'; } $Str .= ' />'; return $Str; @@ -223,7 +350,7 @@ sub radio { $Str .= 'value="'.$value.'"'; } if ($checked eq $value) { - $Str .= ' checked="1"'; + $Str .= ' checked="checked"'; } $Str .= ' />'; return $Str; @@ -253,7 +380,8 @@ dname_hour, dname_min, and dname_sec. The current setting for this time parameter. A unix format time (time in seconds since the beginning of Jan 1st, 1970, GMT. -An undefined value is taken to indicate the value is the current time. +An undefined value is taken to indicate the value is the current time +unless it is requested to leave it empty. See $includeempty. Also, to be explicit, a value of 'now' also indicates the current time. =item $special @@ -263,6 +391,9 @@ the date_setter. See lonparmset for exa =item $includeempty +If it is set (true) and no date/time value is provided, +the date/time fields are left empty. + =item $state Specifies the initial state of the form elements. Either 'disabled' or empty. @@ -280,8 +411,13 @@ The method used to restrict user input w ############################################## sub date_setter { my ($formname,$dname,$currentvalue,$special,$includeempty,$state, - $no_hh_mm_ss,$defhour,$defmin,$defsec) = @_; - my $wasdefined=1; + $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_; + my $now = time; + + my $tzname; + my ($sec,$min,$hour,$mday,$month,$year) = ('', '', undef,''.''.''); + #other potentially useful values: wkday,yrday,is_daylight_savings + if (! defined($state) || $state ne 'disabled') { $state = ''; } @@ -289,40 +425,29 @@ sub date_setter { $no_hh_mm_ss = 0; } if ($currentvalue eq 'now') { - $currentvalue=time; + $currentvalue = $now; } - if ((!defined($currentvalue)) || ($currentvalue eq '')) { - $wasdefined=0; - if ($includeempty) { - $currentvalue = 0; - } else { - $currentvalue = time; - } + + # Default value: Set empty date field to current time + # unless empty inclusion is requested + if ((!$includeempty) && (!$currentvalue)) { + $currentvalue = $now; } - # other potentially useful values: wkday,yrday,is_daylight_savings - my ($sec,$min,$hour,$mday,$month,$year)=('','',undef,'','',''); + # Do we have a date? Split it! if ($currentvalue) { - ($sec,$min,$hour,$mday,$month,$year,undef,undef,undef) = - localtime($currentvalue); - $year += 1900; - } - unless ($wasdefined) { - if (($defhour) || ($defmin) || ($defsec)) { - ($sec,$min,$hour,$mday,$month,$year,undef,undef,undef) = - localtime(time); - $year += 1900; - $sec=($defsec?$defsec:0); - $min=($defmin?$defmin:0); - $hour=($defhour?$defhour:0); - } elsif (!$includeempty) { - $sec=0; - $min=0; - $hour=0; - } + ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue); + + #No values provided for hour, min, sec? Use default 0 + if (($defhour) || ($defmin) || ($defsec)) { + $sec = ($defsec ? $defsec : 0); + $min = ($defmin ? $defmin : 0); + $hour = ($defhour ? $defhour : 0); + } } my $result = "\n\n"; $result .= < + ENDJS - $result .= ' '; + $result .= ' '; my $monthselector = qq{'; # Day my $dayselector = qq{}; # Year - my $yearselector = qq{}; + my $yearselector = qq{}; # my $hourselector = qq{}; - my $cal_link = qq{}; + my $cal_link; + if (!$nolink) { + $cal_link = qq{}; + } # + my $tzone = ' '.$tzname.' '; if ($no_hh_mm_ss) { - $result .= &mt('[_1] [_2] [_3] [_4]Select Date[_5]', - $monthselector,$dayselector,$yearselector, - $cal_link,''); + $result .= &mt('[_1] [_2] [_3] ', + $monthselector,$dayselector,$yearselector). + $tzone; + if (!$nolink) { + $result .= &mt('[_1]Select Date[_2]',$cal_link,''); + } } else { - $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s [_7]Select Date[_8]', - $monthselector,$dayselector,$yearselector, - $hourselector,$minuteselector,$secondselector, - $cal_link,''); + $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ', + $monthselector,$dayselector,$yearselector, + $hourselector,$minuteselector,$secondselector). + $tzone; + if (!$nolink) { + $result .= &mt('[_1]Select Date[_2]',$cal_link,''); + } } - $result .= "\n\n"; + $result .= "\n\n"; return $result; } +sub get_timedates { + my ($epoch) = @_; + my $dt = DateTime->from_epoch(epoch => $epoch) + ->set_time_zone(&Apache::lonlocal::gettimezone()); + my $tzname = $dt->time_zone_short_name(); + my $sec = $dt->second; + my $min = $dt->minute; + my $hour = $dt->hour; + my $mday = $dt->day; + my $month = $dt->month; + if ($month) { + $month --; + } + my $year = $dt->year; + return ($tzname,$sec,$min,$hour,$mday,$month,$year); +} + +sub build_url { + my ($base, $fields)=@_; + my $url; + $url = $base.'?'; + foreach my $key (keys(%$fields)) { + $url.=&escape($key).'='.&escape($$fields{$key}).'&'; + } + $url =~ s/&$//; + return $url; +} + + ############################################## ############################################## @@ -459,7 +624,7 @@ Inputs: =item $dname -The name passed to &datesetter, which prefixes the form elements. +The name passed to &date_setter, which prefixes the form elements. =item $defaulttime @@ -512,20 +677,33 @@ sub get_date_from_form { if (defined($env{'form.'.$dname.'_month'})) { my $tmpmonth = $env{'form.'.$dname.'_month'}; if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) { - $month = $tmpmonth - 1; + $month = $tmpmonth; } } if (defined($env{'form.'.$dname.'_year'})) { my $tmpyear = $env{'form.'.$dname.'_year'}; - if (($tmpyear =~ /^\d+$/) && ($tmpyear > 1900)) { - $year = $tmpyear - 1900; + if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) { + $year = $tmpyear; } } - if (($year<70) || ($year>137)) { return undef; } + if (($year<1970) || ($year>2037)) { return undef; } if (defined($sec) && defined($min) && defined($hour) && - defined($day) && defined($month) && defined($year) && - eval(&timelocal($sec,$min,$hour,$day,$month,$year))) { - return &timelocal($sec,$min,$hour,$day,$month,$year); + defined($day) && defined($month) && defined($year)) { + my $timezone = &Apache::lonlocal::gettimezone(); + my $dt = DateTime->new( year => $year, + month => $month, + day => $day, + hour => $hour, + minute => $min, + second => $sec, + time_zone => $timezone, + ); + my $epoch_time = $dt->epoch; + if ($epoch_time ne '') { + return $epoch_time; + } else { + return undef; + } } else { return undef; } @@ -595,6 +773,8 @@ sub javascript_nothing { ############################################## ############################################## sub javascript_docopen { + my ($mimetype) = @_; + $mimetype ||= 'text/html'; # safari does not understand document.open() and loads "text/html" my $nothing = "''"; my $user_browser; @@ -608,7 +788,7 @@ sub javascript_docopen { if ($user_browser eq 'safari' && $user_os =~ 'mac') { $nothing = "document.clear()"; } else { - $nothing = "document.open('text/html','replace')"; + $nothing = "document.open('$mimetype','replace')"; } return $nothing; } @@ -645,23 +825,18 @@ Returns: a perl string as described. ############################################## ############################################## sub StatusOptions { - my ($status, $formName,$size,$onchange)=@_; + my ($status, $formName,$size,$onchange,$mult)=@_; $size = 1 if (!defined($size)); if (! defined($status)) { $status = 'Active'; $status = $env{'form.Status'} if (exists($env{'form.Status'})); } - my $OpSel1 = ''; - my $OpSel2 = ''; - my $OpSel3 = ''; - - if($status eq 'Any') { $OpSel3 = ' selected'; } - elsif($status eq 'Expired' ) { $OpSel2 = ' selected'; } - else { $OpSel1 = ' selected'; } - my $Str = ''; $Str .= ''."\n"; } @@ -812,32 +993,32 @@ sub Create_PrgWin { #the whole function called through timeout is due to issues #in mozilla Read BUG #2665 if you want to know the whole story - &r_print($r,'"); + "\nwindow.setTimeout(openpopwin,0)" + )); $prog_state{'formname'}='popremain'; $prog_state{'inputname'}="remaining"; } elsif ($type eq 'inline') { $prog_state{'window'}='window'; if (!$formname) { $prog_state{'formname'}=&get_uniq_name(); - &r_print($r,'
'); + &r_print($r,''); } else { $prog_state{'formname'}=$formname; } if (!$inputname) { $prog_state{'inputname'}=&get_uniq_name(); - &r_print($r,$heading.' '); + &r_print($r,&mt("$heading [_1]",' ')); } else { $prog_state{'inputname'}=$inputname; @@ -857,10 +1038,12 @@ sub Create_PrgWin { # update progress sub Update_PrgWin { my ($r,$prog_state,$displayString)=@_; - &r_print($r,''); + &r_print($r,&Apache::lonhtmlcommon::scripttag( + $$prog_state{'window'}.'.document.'. + $$prog_state{'formname'}.'.'. + $$prog_state{'inputname'}.'.value="'. + $displayString.'";' + )); $$prog_state{'laststart'}=&Time::HiRes::time(); } @@ -913,11 +1096,13 @@ sub Increment_PrgWin { if ($user_browser eq 'explorer' && $user_os =~ 'mac') { $lasttime = ''; } - &r_print($r,''); + &r_print($r,&Apache::lonhtmlcommon::scripttag( + $$prog_state{'window'}.'.document.'. + $$prog_state{'formname'}.'.'. + $$prog_state{'inputname'}.'.value="'. + $$prog_state{'done'}.'/'.$$prog_state{'max'}. + ': '.$time_est.' '.&mt('remaining').' '.$lasttime.'";' + )); $$prog_state{'laststart'}=&Time::HiRes::time(); } @@ -925,7 +1110,9 @@ sub Increment_PrgWin { sub Close_PrgWin { my ($r,$prog_state)=@_; if ($$prog_state{'type'} eq 'popup') { - &r_print($r,''."\n"); + &r_print($r,&Apache::lonhtmlcommon::scripttag( + 'popwin.close()' + )); } elsif ($$prog_state{'type'} eq 'inline') { &Update_PrgWin($r,$prog_state,&mt('Done')); } @@ -945,35 +1132,45 @@ sub r_print { # ------------------------------------------------------- Puts directory header sub crumbs { - my ($uri,$target,$prefix,$form,$size,$noformat)=@_; - if (! defined($size)) { - $size = '+2'; - } + my ($uri,$target,$prefix,$form,$skiplast)=@_; if ($target) { $target = ' target="'. &Apache::loncommon::escape_single($target).'"'; } - my $output=''; - unless ($noformat) { $output.='
'; } - $output.=''.$prefix.'/'; - if ($env{'user.adv'}) { - my $path=$prefix.'/'; - foreach my $dir (split('/',$uri)) { + my $output=''; + $output.=$prefix.'/'; + if (($env{'user.adv'}) || ($env{'user.author'})) { + my $path=$prefix.'/'; + foreach my $dir (split('/',$uri)) { if (! $dir) { next; } $path .= $dir; - unless ($path eq $uri) { $path.='/'; } - my $linkpath = &Apache::loncommon::escape_single($path); + if ($path eq $uri) { + if ($skiplast) { + $output.=$dir; + last; + } + } else { + $path.='/'; + } + my $href_path = &HTML::Entities::encode($path,'<>&"'); + &Apache::loncommon::inhibit_menu_check(\$href_path); if ($form) { - $linkpath= - qq{javascript:$form.action='$linkpath';$form.submit();}; + my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();'; + $output.=qq{$dir/}; + } else { + $output.=qq{$dir/}; } - $output.=qq{$dir/}; - } + } } else { - $output.=$uri; + foreach my $dir (split('/',$uri)) { + if (! $dir) { next; } + $output.=$dir.'/'; + } } - unless ($uri=~/\/$/) { $output=~s/\/$//; } - return $output.''.($noformat?'':'
'); + if ($uri !~ m|/$|) { $output=~s|/$||; } + $output.=''; + + return $output; } # --------------------- A function that generates a window for the spellchecker @@ -981,24 +1178,32 @@ sub crumbs { sub spellheader { my $start_page= &Apache::loncommon::start_page('Speller Suggestions',undef, - {'only_body' => 1, - 'js_ready' => 1, - 'bgcolor' => '#DDDDDD',}); + {'only_body' => 1, + 'js_ready' => 1, + 'bgcolor' => '#DDDDDD', + 'add_entries' => { + 'onload' => + 'document.forms.spellcheckform.submit()', + } + }); my $end_page= &Apache::loncommon::end_page({'js_ready' => 1}); my $nothing=&javascript_nothing(); return (< +// $end_page'); + checkwin.document.writeln('$start_page
<\\/form>$end_page'); checkwin.document.close(); } // END LON-CAPA Internal --> +// ]]> ENDCHECK } @@ -1009,7 +1214,7 @@ sub spelllink { my ($form,$field)=@_; my $linktext=&mt('Check Spelling'); return (<$linktext +$linktext ENDLINK } @@ -1032,43 +1237,18 @@ ENDLINK } sub htmlareaheaders { - if (&htmlareablocked()) { return ''; } - unless (&htmlareabrowser()) { return ''; } - my $lang='en'; - if (&mt('htmlarea_lang') ne 'htmlarea_lang') { - $lang=&mt('htmlarea_lang'); - } - return (< -_editor_url='/htmlarea/'; -_editor_lang='$lang'; - - -ENDHEADERS -} - -# ------------------------------------------------- Activate additional buttons - -sub htmlareaaddbuttons { - if (&htmlareablocked()) { return ''; } - unless (&htmlareabrowser()) { return ''; } - return (<\$','\$ '); - } - ); - config.registerButton('ed_math_eqn','LaTeX Equation', - '/htmlarea/images/ed_math_eqn.gif',false, - function(editor,id) { - editor.surroundHTML( - ' \\n
\\\\[','\\\\]
\\n '); - } - ); - config.toolbar.push(['ed_math','ed_math_eqn']); -ENDADDBUTTON + my $s=""; + if (&htmlareabrowser()) { + $s.=(< +ENDEDITOR + } + $s.=(< + + +ENDJQUERY + return $s; } # ----------------------------------------------------------------- Preferences @@ -1078,7 +1258,7 @@ sub disablelink { if (defined($#fields)) { unless ($#fields>=0) { return ''; } } - return ''.&mt('Disable WYSIWYG Editor').''; + return ''.&mt('Disable WYSIWYG Editor').''; } sub enablelink { @@ -1086,7 +1266,16 @@ sub enablelink { if (defined($#fields)) { unless ($#fields>=0) { return ''; } } - return ''.&mt('Enable WYSIWYG Editor').''; + return ''.&mt('Enable WYSIWYG Editor').''; +} + +# ------------------------------------------------- lang to use in html editor +sub htmlarea_lang { + my $lang='en'; + if (&mt('htmlarea_lang') ne 'htmlarea_lang') { + $lang=&mt('htmlarea_lang'); + } + return $lang; } # ----------------------------------------- Script to activate only some fields @@ -1094,13 +1283,81 @@ sub enablelink { sub htmlareaselectactive { my @fields=@_; unless (&htmlareabrowser()) { return ''; } - if (&htmlareablocked()) { return '
'.&enablelink(@fields); } - my $output='
". + + function startRichEditor(id) { + CKEDITOR.replace(id, + { + customConfig: "/ckeditor/loncapaconfig.js" + } + ); + } + + function destroyRichEditor(id) { + CKEDITOR.instances[id].destroy(); + } + + function editorHandler(event) { + var rawid = $(this).attr("id"); + var id = new RegExp("LC_rt_(.*)").exec(rawid)[1] + event.preventDefault(); + if ($(this).hasClass("LC_enable_rt")) { + startRichEditor(id); + $("#LC_rt_"+id).html("« Plain text"); + $("#LC_rt_"+id).attr("title", "Disable rich text formatting and edit in plain text"); + $("#LC_rt_"+id).addClass("LC_disable_rt"); + $("#LC_rt_"+id).removeClass("LC_enable_rt"); + } else { + destroyRichEditor(id); + $("#LC_rt_"+id).html("Rich formatting »"); + $("#LC_rt_"+id).attr("title", "Enable rich text formatting (bold, italic, etc.)"); + $("#LC_rt_"+id).addClass("LC_enable_rt"); + $("#LC_rt_"+id).removeClass("LC_disable_rt"); + } + } + + $(document).ready(function(){ + $(".LC_richAlwaysOn").each(function() { + startRichEditor($(this).attr("id")); + }); + $(".LC_richDetectHtml").each(function() { + var id = $(this).attr("id"); + if(containsBlockHtml(id)) { + $(this).before(""); + startRichEditor(id); + $("#LC_rt_"+id).click(editorHandler); + } + else { + $(this).before(""); + $("#LC_rt_"+id).click(editorHandler); + } + }); + $(".LC_richDefaultOn").each(function() { + var id = $(this).attr("id"); + $(this).before(""); + startRichEditor(id); + $("#LC_rt_"+id).click(editorHandler); + }); + $(".LC_richDefaultOff").each(function() { + var id = $(this).attr("id"); + $(this).before(""); + $("#LC_rt_"+id).click(editorHandler); + }); + + }); +'; + $output.="\nwindow.status='Activated Editfields';\n" + .'// ]]>'."\n" + .'
'. &disablelink(@fields); return $output; } @@ -1126,21 +1383,19 @@ sub htmlareabrowser { =item breadcrumbs Compiles the previously registered breadcrumbs into an series of links. -FAQ and BUG links will be placed on the left side of the table if they -are defined for the last registered breadcrumb. Additionally supports a 'component', which will be displayed on the -right side of the table (without a link). +right side of the breadcrumbs enclosing div (without a link). A link to help for the component will be included if one is specified. All inputs can be undef without problems. -Inputs: $color (the background color of the table returned), - $component (the large text on the right side of the table), +Inputs: $component (the text on the right side of the breadcrumbs trail), $component_help - $function (role to get colors from) - $domain (domian of role) $menulink (boolean, controls whether to include a link to /adm/menu) - + $helplink (if 'nohelp' don't include the orange help link) + $css_class (optional name for the class to apply to the table for CSS) + $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component + when including the text on the right. Returns a string containing breadcrumbs for the current page. =item clear_breadcrumbs @@ -1153,7 +1408,8 @@ Pushes a breadcrumb on the stack of crum input: $breadcrumb, a hash reference. The keys 'href','title', and 'text' are required. If present the keys 'faq' and 'bug' will be used to provide -links to the FAQ and bug sites. +links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' +and 'text' values won't be sent through &mt() returns: nothing @@ -1163,67 +1419,74 @@ returns: nothing ############################################################ { my @Crumbs; + my %tools = (); sub breadcrumbs { - my ($color,$component,$component_help,$function,$domain,$menulink, - $helplink) = @_; - if (! defined($color)) { - if (! defined($function)) { - $function = &Apache::loncommon::get_users_function(); - } - $color = &Apache::loncommon::designparm($function.'.tabbg', - $domain); - } - # - my $Str = "\n". - ''. - ''; - # - if (defined($component)) { - $Str .= ''; + + + unless ($CourseBreadcrumbs) { + $links = htmltag('ol', $links, { id => "LC_MenuBreadcrumbs" }); + } else { + $links = htmltag('ul', $links, { class => "LC_CourseBreadcrumbs" }); } - $Str .= '
'. - ''; + my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, $CourseBreadcrumbs) = @_; # + $css_class ||= 'LC_breadcrumbs'; + # Make the faq and bug data cascade - my $faq = ''; - my $bug = ''; - my $help=''; + my $faq = ''; + my $bug = ''; + my $help = ''; + # Crumb Symbol + my $crumbsymbol = '»'; # The last breadcrumb does not have a link, so handle it separately. my $last = pop(@Crumbs); # # The first one should be the course or a menu link - if (!defined($menulink)) { $menulink=1; } + if (!defined($menulink)) { $menulink=1; } if ($menulink) { my $description = 'Menu'; + my $no_mt_descr = 0; if (exists($env{'request.course.id'}) && $env{'request.course.id'} ne '') { $description = $env{'course.'.$env{'request.course.id'}.'.description'}; + $no_mt_descr = 1; } - unshift(@Crumbs,{ - href =>'/adm/menu', - title =>'Go to main menu', - target =>'_top', - text =>$description, - }); - } - my $links .= - join('->', - map { - $faq = $_->{'faq'} if (exists($_->{'faq'})); - $bug = $_->{'bug'} if (exists($_->{'bug'})); - $help = $_->{'help'} if (exists($_->{'help'})); - my $result = '{'target'}) && $_->{'target'} ne '') { - $result .= 'target="'.$_->{'target'}.'" '; - } - $result .='title="'.&mt($_->{'title'}).'">'. - &mt($_->{'text'}).''; - $result; - } @Crumbs - ); - $links .= '->' if ($links ne ''); - $links .= ''.&mt($last->{'text'}).''; - # + $menulink = { href =>'/adm/menu', + title =>'Go to main menu', + target =>'_top', + text =>$description, + no_mt =>$no_mt_descr, }; + if($last) { + #$last set, so we have some crumbs + unshift(@Crumbs,$menulink); + } else { + #only menulink crumb present + $last = $menulink; + } + } + my $links = join "", + map { + $faq = $_->{'faq'} if (exists($_->{'faq'})); + $bug = $_->{'bug'} if (exists($_->{'bug'})); + $help = $_->{'help'} if (exists($_->{'help'})); + + my $result = $_->{no_mt} ? $_->{text} : mt($_->{text}); + + if ($_->{href}){ + $result = htmltag( 'a', $result, + { href => $_->{href}, + title => $_->{no_mt} ? $_->{title} : mt($_->{title}), + target => $_->{target}, }); + } + + $result = htmltag( 'li', "$result $crumbsymbol"); + } @Crumbs; + + #should the last Element be translated? + + my $lasttext = $last->{'no_mt'} ? $last->{'text'} + : mt( $last->{'text'} ); + + $links .= htmltag( 'li', htmltag('b', $lasttext), {title => $lasttext}); + my $icons = ''; - $faq = $last->{'faq'} if (exists($last->{'faq'})); - $bug = $last->{'bug'} if (exists($last->{'bug'})); + $faq = $last->{'faq'} if (exists($last->{'faq'})); + $bug = $last->{'bug'} if (exists($last->{'bug'})); $help = $last->{'help'} if (exists($last->{'help'})); $component_help=($component_help?$component_help:$help); # if ($faq ne '') { @@ -1232,34 +1495,146 @@ returns: nothing # if ($bug ne '') { # $icons .= &Apache::loncommon::help_open_bug($bug); # } - if ($helplink ne 'nohelp') { - $icons .= &Apache::loncommon::help_open_menu($color,$component,$component_help,$function,$faq,$bug); - } - if ($icons ne '') { - $Str .= $icons.' '; + if ($faq ne '' || $component_help ne '' || $bug ne '') { + $icons .= &Apache::loncommon::help_open_menu($component, + $component_help, + $faq,$bug); } # - $Str .= $links.''. - ''.&mt($component).'
'."\n"; - # + + if ($component) { + $links = htmltag('span', + ( $no_mt ? $component : mt($component) ). + ( $icons ? $icons : '' ), + { class => 'LC_breadcrumbs_component' } ) + .$links; + } + + render_tools(\$links); + $links = htmltag('div', $links, + { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ; + render_advtools(\$links); + # Return the @Crumbs stack to what we started with push(@Crumbs,$last); shift(@Crumbs); - # - return $Str; + # Return the breadcrumb's line + return "$links"; } sub clear_breadcrumbs { undef(@Crumbs); + undef(%tools); } sub add_breadcrumb { - push (@Crumbs,@_); + push(@Crumbs,@_); + } + +=item add_breadcrumb_tool($category, $html) + +Adds $html to $category of the breadcrumb toolbar container. + +$html is usually a link to a page that invokes a function on the currently +displayed data (e.g. print when viewing a problem) + +Currently there are 3 possible values for $category: + +=over + +=item navigation +left of breadcrumbs line + +=item tools +right of breadcrumbs line + +=item advtools +advanced tools shown in a separate box below breadcrumbs line + +=back + +returns: nothing + +=cut + + sub add_breadcrumb_tool { + my ($category, @html) = @_; + return unless @html; + if (!defined(%tools)) { + %tools = ( navigation => [], tools => [], advtools => []); + } + + #this cleans data received from lonmenu::innerregister + @html = grep {defined $_ && $_ ne ''} @html; + for (@html) { + s/align="(right|left)"//; + s/// if $category ne 'advtools'; + } + + push @{$tools{$category}}, @html; + } + +=item clear_breadcrumb_tools() + +Clears the breadcrumb toolbar container. + +returns: nothing + +=cut + + sub clear_breadcrumb_tools { + undef(%tools); + } + +=item render_tools(\$breadcrumbs) + +Creates html for breadcrumb tools (categories navigation and tools) and inserts +\$breadcrumbs at the correct position. + +input: \$breadcrumbs - a reference to the string containing prepared +breadcrumbs. + +returns: nothing +=cut + +#TODO might split this in separate functions for each category + sub render_tools { + my ($breadcrumbs) = @_; + return unless defined %tools; + + my $navigation = list_from_array($tools{navigation}, + { listattr => { class=>"LC_breadcrumb_tools_navigation" } }); + my $tools = list_from_array($tools{tools}, + { listattr => { class=>"LC_breadcrumb_tools_tools" } }); + $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs], + { listattr => { class=>'LC_breadcrumb_tools_outerlist' } }); + } + +=item render_advtools(\$breadcrumbs) + +Creates html for advanced tools (category advtools) and inserts \$breadcrumbs +at the correct position. + +input: \$breadcrumbs - a reference to the string containing prepared +breadcrumbs (after render_tools call). + +returns: nothing +=cut + + sub render_advtools { + my ($breadcrumbs) = @_; + return unless (defined $tools{'advtools'}) + and (scalar(@{$tools{'advtools'}}) > 0); + + $$breadcrumbs .= Apache::loncommon::head_subbox( + funclist_from_array($tools{'advtools'}) ); } } # End of scope for @Crumbs @@ -1278,8 +1653,8 @@ returns: nothing # row1 # row2 # row3 ... etc. -# &submit_row(0 -# &end_pickbox() +# &submit_row() +# &end_pick_box() # # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row, # &status_select_row and &email_default_row @@ -1320,86 +1695,117 @@ returns: nothing # routines, but can also be called directly to start and end rows which have # needs that are not accommodated by the *_select_row() routines. +{ # Start: row_count block for pick_box +my @row_count; + sub start_pick_box { - my ($table_width) = @_; + my ($css_class) = @_; + if (defined($css_class)) { + $css_class = 'class="'.$css_class.'"'; + } else { + $css_class= 'class="LC_pick_box"'; + } + unshift(@row_count,0); my $output = <<"END"; - - - - -
- - - - -
- +
END return $output; } sub end_pick_box { + shift(@row_count); my $output = <<"END";
-
-
+END + return $output; +} + +sub row_headline { + my $output = <<"END"; + END return $output; } sub row_title { - my ($col_width,$tablecolor,$title) = @_; + my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_; + $row_count[0]++; + my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row'; + $css_title_class ||= 'LC_pick_box_title'; + $css_title_class = 'class="'.$css_title_class.'"'; + + $css_value_class ||= 'LC_pick_box_value'; + + if ($title ne '') { + $title .= ':'; + } my $output = <<"ENDONE"; - - - - - - -
$title: -
+ + + $title - - - + -
ENDONE return $output; } sub row_closure { + my ($no_separator) =@_; my $output = <<"ENDTWO"; -
+ENDTWO + if (!$no_separator) { + $output .= <<"ENDTWO"; - -
+ ENDTWO + } return $output; } +} # End: row_count block for pick_box + + sub role_select_row { - my ($roles,$col_width,$tablecolor,$title) = @_; + my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_; + my $crstype = 'Course'; + if ($cdom ne '' && $cnum ne '') { + $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum); + } my $output; if (defined($title)) { - $output = &row_title($col_width,$tablecolor,$title); + $output = &row_title($title,$css_class); } - $output .= qq| - \n|; foreach my $role (@$roles) { my $plrole; if ($role eq 'ow') { $plrole = &mt('Course Owner'); + } elsif ($role eq 'cr') { + if ($show_separate_custom) { + if ($cdom ne '' && $cnum ne '') { + my %course_customroles = &course_custom_roles($cdom,$cnum); + foreach my $crrole (sort(keys(%course_customroles))) { + my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|); + $output .= ' '; + } + } + } else { + $plrole = &mt('Custom Role'); + } } else { - $plrole=&Apache::lonnet::plaintext($role); + $plrole=&Apache::lonnet::plaintext($role,$crstype); + } + if (($role ne 'cr') || (!$show_separate_custom)) { + $output .= ' '; } - $output .= ' '; } - $output .= qq| - \n|; + $output .= qq| \n|; if (defined($title)) { $output .= &row_closure(); } @@ -1407,11 +1813,19 @@ sub role_select_row { } sub course_select_row { - my ($col_width,$tablecolor,$title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles) = @_; - my $output = &row_title($col_width,$tablecolor,$title); - $output .= " \n"; - $output .= qq| - |; + + my ($allcrs,$pickspec); + if ($crstype eq 'Community') { + $allcrs = &mt('All communities'); + $pickspec = &mt('Pick specific communities:'); + } else { + $allcrs = &mt('All courses'); + $pickspec = &mt('Pick specific course(s):'); + } + my $courseform=''.&Apache::loncommon::selectcourse_link - ($formname,'pickcourse','pickdomain','coursedesc','',1).''; + ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).''; + $output .= ''.$allcrs.'
'; if ($totcodes > 0) { - $output .= ''.&mt('All courses'); my $numtitles = @$codetitles; if ($numtitles > 0) { - $output .= '
'.&mt('Pick courses by category:').'
'; + $output .= ''.&mt('Pick courses by category:').'
'; $output .= '
'.$$codetitles[0].'
'."\n". '

'; } } - $output .= ''.&mt('Pick specific course(s):').' '.$courseform.'  selected.
'."\n"; - $output .= &row_closure(); + $output .= ''.$pickspec.' '.$courseform.'  selected.
'."\n"; return $output; } sub status_select_row { - my ($types,$col_width,$tablecolor,$title) = @_; + my ($types,$title,$css_class) = @_; my $output; if (defined($title)) { - $output = &row_title($col_width,$tablecolor,$title); + $output = &row_title($title,$css_class,'LC_pick_box_select'); } - $output .= qq| - \n|; foreach my $status_type (sort(keys(%{$types}))) { $output .= ' '; } - $output .= qq| - \n|; + $output .= qq| \n|; if (defined($title)) { $output .= &row_closure(); } @@ -1508,18 +1931,17 @@ sub status_select_row { } sub email_default_row { - my ($authtypes,$col_width,$tablecolor,$title,$descrip) = @_; - my $output = &row_title($col_width,$tablecolor,$title); - my @rowcols = ('#eeeeee','#dddddd'); - $output .= ' '.$descrip; - $output .= &start_pick_box(''); - $output .= ' - '.&mt('Authentication Method').''.&mt('Username -> e-mail conversion').' - '."\n"; + my ($authtypes,$title,$descrip,$css_class) = @_; + my $output = &row_title($title,$css_class); + $output .= $descrip. + &Apache::loncommon::start_data_table(). + &Apache::loncommon::start_data_table_header_row(). + ''.&mt('Authentication Method').''. + ''.&mt('Username -> e-mail conversion').''."\n". + &Apache::loncommon::end_data_table_header_row(); my $rownum = 0; foreach my $auth (sort(keys(%{$authtypes}))) { my ($userentry,$size); - my $rowiter = $rownum%2; if ($auth =~ /^krb/) { $userentry = ''; $size = 25; @@ -1527,32 +1949,72 @@ sub email_default_row { $userentry = 'username@'; $size = 15; } - $output .= ' '.$$authtypes{$auth}.''.$userentry.''; - $rownum ++; + $output .= &Apache::loncommon::start_data_table_row(). + ' '.$$authtypes{$auth}.''. + ''.$userentry. + ''. + &Apache::loncommon::end_data_table_row(); } - $output .= &end_pick_box(); - $output .= "
\n"; + $output .= &Apache::loncommon::end_data_table(); $output .= &row_closure(); return $output; } sub submit_row { - my ($col_width,$tablecolor,$title,$cmd,$submit_text) = @_; - my $output = &row_title($col_width,$tablecolor,$title); + my ($title,$cmd,$submit_text,$css_class) = @_; + my $output = &row_title($title,$css_class,'LC_pick_box_submit'); $output .= qq| -
 

- \n|; + \n|; return $output; } +sub course_custom_roles { + my ($cdom,$cnum) = @_; + my %returnhash=(); + my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); + foreach my $person (sort(keys(%coursepersonnel))) { + my ($role) = ($person =~ /^([^:]+):/); + my ($end,$start) = split(/:/,$coursepersonnel{$person}); + if ($end == -1 && $start == -1) { + next; + } + if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) { + $returnhash{$role} ++; + } + } + return %returnhash; +} + + +############################################## +############################################## + +# topic_bar +# +# Generates a div containing an (optional) number with a white background followed by a +# title with a background color defined in the corresponding CSS: LC_topic_bar +# Inputs: +# 1. number to display. +# If input for number is empty only the title will be displayed. +# 2. title text to display. +# Outputs - a scalar containing html mark-up for the div. + +sub topic_bar { + my ($num,$title) = @_; + my $number = ''; + if ($num ne '') { + $number = ''.$num.''; + } + return '
'.$number.$title.'
'; +} + ############################################## ############################################## - # echo_form_input # # Generates html markup to add form elements from the referrer page @@ -1617,7 +2079,6 @@ sub echo_form_input { ############################################## ############################################## - # set_form_elements # # Generates javascript to set form elements to values based on @@ -1682,72 +2143,74 @@ sub set_form_elements { $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g; $values{$name}[$i] =~ s/"/\\"/g; } - if ($$elements{$name} eq 'text') { + if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) { my $numvalues = @{$values{$name}}; if ($numvalues > 1) { my $valuestring = join('","',@{$values{$name}}); $output .= qq| var textvalues = new Array ("$valuestring"); - var total = courseForm.$name.length; + var total = courseForm.elements['$name'].length; if (total > $numvalues) { total = $numvalues; } for (var i=0; i= 0) { + return true; + } + return false; + } +} +END + return $scripttag; +} + + +# USAGE: htmltag(element, content, {attribute => value,...}); +# +# EXAMPLES: +# - htmltag('a', 'this is an anchor', {href => 'www.example.com', +# title => 'this is a title'}) +# +# - You might want to set up needed tags like: +# +# my $h3 = sub { return htmltag( "h3", @_ ) }; +# +# ... and use them: $h3->("This is a headline") +# +# - To set up a couple of tags, see sub inittags +# +# NOTES: +# - Empty elements, such as
are correctly terminated, +# i.e. htmltag('br') returns
+# - Empty attributes (title="") are filtered out. +# - The function will not check for deprecated attributes. +# +# OUTPUT: content enclosed in xhtml conform tags +sub htmltag{ + return + qq|<$_[0]| + . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } ) + . ($_[1] ? qq|>$_[1]| : qq|/>|). "\n"; +}; + + +# USAGE: inittags(@tags); +# +# EXAMPLES: +# - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) ) +# $h1->("This is a headline") #Returns:

This is a headline

+# +# NOTES: See sub htmltag for further information. +# +# OUTPUT: List of subroutines. +sub inittags { + my @tags = @_; + return map { my $tag = $_; + sub { return htmltag( $tag, @_ ) } + } @tags; +} + + +# USAGE: scripttag(scriptcode, [start|end|both]); +# +# EXAMPLES: +# - scripttag("alert('Hello World!')", 'both') +# returns: +# +# +# NOTES: +# - works currently only for javascripts +# +# OUTPUT: +# Scriptcode properly enclosed in