File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.282: download - view: text, annotated - select for diffs
Sun Aug 8 02:00:38 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_0_RC1, HEAD
- Replacement of user's environment.wysiwygeditor with link to switch to/from
  CKEditor 3 Richtext editor on textareas where needed.
- Rich text editor link available for Text/HTML block in colorful editor
- Eliminate duplicate Richtext link for textarea entry fields
- "Edit Math" button hidden when richtext editor enabled - use <span> instead
  of <div> for more compact display.
- Help icon for "Edit Math" hidden by switching img src from help.png to
  transparent gif. Additional arg to loncommon::help_open_topic() is
  imgid - id of img tag for icon associated with each "Edit Math" button.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common html routines
    3: #
    4: # $Id: lonhtmlcommon.pm,v 1.282 2010/08/08 02:00:38 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ######################################################################
   29: ######################################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::lonhtmlcommon - routines to do common html things
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Referenced by other mod_perl Apache modules.
   40: 
   41: =head1 INTRODUCTION
   42: 
   43: lonhtmlcommon is a collection of subroutines used to present information
   44: in a consistent html format, or provide other functionality related to
   45: html.
   46: 
   47: =head2 General Subroutines
   48: 
   49: =over 4
   50: 
   51: =cut 
   52: 
   53: ######################################################################
   54: ######################################################################
   55: 
   56: package Apache::lonhtmlcommon;
   57: 
   58: use strict;
   59: use Time::Local;
   60: use Time::HiRes;
   61: use Apache::lonlocal;
   62: use Apache::lonnet;
   63: use LONCAPA;
   64: 
   65: 
   66: sub coursepreflink {
   67:    my ($text,$category)=@_;
   68:    if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
   69:       return '<a href="'.&HTML::Entities::encode("/adm/courseprefs?phase=display&actions=$category",'<>&"').'">'.$text.'</a>';
   70:    } else {
   71:       return '';
   72:    }
   73: }
   74: 
   75: sub raw_href_to_link {
   76:    my ($message)=@_;
   77:    $message=~s/(https?\:\/\/[^\s\'\"\<]+)([\s\<]|$)/<a href="$1"><tt>$1<\/tt><\/a>$2/gi;
   78:    return $message;
   79: }
   80: 
   81: ##############################################
   82: ##############################################
   83: 
   84: =item confirm_success
   85: 
   86: Successful completion of an operation message
   87: 
   88: =cut
   89: 
   90: sub confirm_success {
   91:    my ($message,$failure)=@_;
   92:    if ($failure) {
   93:       return '<span class="LC_error" style="font-size: inherit;">'."\n"
   94:             .'<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.&mt('Error').'" /> '."\n"
   95:             .$message."\n"
   96:             .'</span>'."\n";
   97:    } else {
   98:       return '<span class="LC_success">'."\n"
   99:             .'<img src="/adm/lonIcons/navmap.correct.gif" alt="'.&mt('OK').'" /> '."\n"
  100:             .$message."\n"
  101:             .'</span>'."\n";
  102:    }
  103: }
  104: 
  105: ##############################################
  106: ##############################################
  107: 
  108: =pod
  109: 
  110: =item dragmath_button
  111: 
  112: Creates a button that launches a dragmath popup-window, in which an 
  113: expression can be edited and pasted as LaTeX into a specified textarea. 
  114: 
  115:   textarea - Name of the textarea to edit.
  116:   helpicon - If true, show a help icon to the right of the button.
  117: 
  118: =cut
  119: 
  120: sub dragmath_button {
  121:     my ($textarea,$helpicon) = @_;
  122:     my $help_text; 
  123:     if ($helpicon) {
  124:         $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor',undef,undef,undef,undef,'mathhelpicon_'.$textarea);
  125:     }
  126:     my $buttontext=&mt('Edit Math');
  127:     return <<ENDDRAGMATH;
  128:                 <input type="button" value="$buttontext" onclick="javascript:mathedit('$textarea',document)" />$help_text
  129: ENDDRAGMATH
  130: }
  131: 
  132: ##############################################
  133: 
  134: =pod
  135: 
  136: =item dragmath_js
  137: 
  138: Javascript used to open pop-up window containing dragmath applet which 
  139: can be used to paste LaTeX into a textarea.
  140: =cut
  141: 
  142: sub dragmath_js {
  143:     my ($popup) = @_;
  144:     return <<ENDDRAGMATHJS;
  145:                 <script type="text/javascript">
  146:                 // <![CDATA[
  147:                   function mathedit(textarea, doc) {
  148:                      targetEntry = textarea;
  149:                      targetDoc   = doc;
  150:                      newwin  = window.open("/adm/dragmath/applet/$popup.html","","width=565,height=500,resizable");
  151:                   }
  152:                 // ]]>
  153:                 </script>
  154: 
  155: ENDDRAGMATHJS
  156: }
  157: 
  158: 
  159: ##############################################
  160: ##############################################
  161: 
  162: =pod
  163: 
  164: =item authorbombs
  165: 
  166: =cut
  167: 
  168: ##############################################
  169: ##############################################
  170: 
  171: sub authorbombs {
  172:     my $url=shift;
  173:     $url=&Apache::lonnet::declutter($url);
  174:     my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
  175:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
  176:     foreach my $bomb (keys(%bombs)) {
  177: 	if ($bomb =~ /^$udom\/$uname\//) {
  178: 	    return '<a href="/adm/bombs/'.$url.
  179: 		'"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" alt="'.&mt('Bomb').'" border="0" /></a>'.
  180: 		&Apache::loncommon::help_open_topic('About_Bombs');
  181: 	}
  182:     }
  183:     return '';
  184: }
  185: 
  186: ##############################################
  187: ##############################################
  188: 
  189: sub recent_filename {
  190:     my $area=shift;
  191:     return 'nohist_recent_'.&escape($area);
  192: }
  193: 
  194: sub store_recent {
  195:     my ($area,$name,$value,$freeze)=@_;
  196:     my $file=&recent_filename($area);
  197:     my %recent=&Apache::lonnet::dump($file);
  198:     if (scalar(keys(%recent))>20) {
  199: # remove oldest value
  200: 	my $oldest=time();
  201: 	my $delkey='';
  202: 	foreach my $item (keys(%recent)) {
  203: 	    my $thistime=(split(/\&/,$recent{$item}))[0];
  204: 	    if (($thistime ne "always_include") && ($thistime<$oldest)) {
  205: 		$oldest=$thistime;
  206: 		$delkey=$item;
  207: 	    }
  208: 	}
  209: 	&Apache::lonnet::del($file,[$delkey]);
  210:     }
  211: # store new value
  212:     my $timestamp;
  213:     if ($freeze) {
  214:         $timestamp = "always_include";
  215:     } else {
  216:         $timestamp = time();
  217:     }   
  218:     &Apache::lonnet::put($file,{ $name => 
  219: 				 $timestamp.'&'.&escape($value) });
  220: }
  221: 
  222: sub remove_recent {
  223:     my ($area,$names)=@_;
  224:     my $file=&recent_filename($area);
  225:     return &Apache::lonnet::del($file,$names);
  226: }
  227: 
  228: sub select_recent {
  229:     my ($area,$fieldname,$event)=@_;
  230:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  231:     my $return="\n<select name='$fieldname'".
  232: 	($event?" onchange='$event'":'').
  233: 	">\n<option value=''>--- ".&mt('Recent')." ---</option>";
  234:     foreach my $value (sort(keys(%recent))) {
  235: 	unless ($value =~/^error\:/) {
  236: 	    my $escaped = &Apache::loncommon::escape_url($value);
  237: 	    &Apache::loncommon::inhibit_menu_check(\$escaped);
  238:             if ($area eq 'residx') {
  239:                 next if ((!&Apache::lonnet::allowed('bre',$value)) && (!&Apache::lonnet::allowed('bro',$value)));
  240:             }
  241: 	    $return.="\n<option value='$escaped'>".
  242: 		&unescape((split(/\&/,$recent{$value}))[1]).
  243: 		'</option>';
  244: 	}
  245:     }
  246:     $return.="\n</select>\n";
  247:     return $return;
  248: }
  249: 
  250: sub get_recent {
  251:     my ($area, $n) = @_;
  252:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  253: 
  254: # Create hash with key as time and recent as value
  255: # Begin filling return_hash with any 'always_include' option
  256:     my %time_hash = ();
  257:     my %return_hash = ();
  258:     foreach my $item (keys(%recent)) {
  259:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  260:         if ($thistime eq 'always_include') {
  261:             $return_hash{$item} = &unescape($thisvalue);
  262:             $n--;
  263:         } else {
  264:             $time_hash{$thistime} = $item;
  265:         }
  266:     }
  267: 
  268: # Sort by decreasing time and return key value pairs
  269:     my $idx = 1;
  270:     foreach my $item (reverse(sort(keys(%time_hash)))) {
  271:        $return_hash{$time_hash{$item}} =
  272:                   &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
  273:        if ($n && ($idx++ >= $n)) {last;}
  274:     }
  275: 
  276:     return %return_hash;
  277: }
  278: 
  279: sub get_recent_frozen {
  280:     my ($area) = @_;
  281:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  282: 
  283: # Create hash with all 'frozen' items
  284:     my %return_hash = ();
  285:     foreach my $item (keys(%recent)) {
  286:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  287:         if ($thistime eq 'always_include') {
  288:             $return_hash{$item} = &unescape($thisvalue);
  289:         }
  290:     }
  291:     return %return_hash;
  292: }
  293: 
  294: 
  295: 
  296: =pod
  297: 
  298: =item textbox
  299: 
  300: =cut
  301: 
  302: ##############################################
  303: ##############################################
  304: sub textbox {
  305:     my ($name,$value,$size,$special) = @_;
  306:     $size = 40 if (! defined($size));
  307:     $value = &HTML::Entities::encode($value,'<>&"');
  308:     my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
  309:         'value="'.$value.'" '.$special.' />';
  310:     return $Str;
  311: }
  312: 
  313: ##############################################
  314: ##############################################
  315: 
  316: =pod
  317: 
  318: =item checkbox
  319: 
  320: =cut
  321: 
  322: ##############################################
  323: ##############################################
  324: sub checkbox {
  325:     my ($name,$checked,$value) = @_;
  326:     my $Str = '<input type="checkbox" name="'.$name.'" ';
  327:     if (defined($value)) {
  328:         $Str .= 'value="'.$value.'"';
  329:     } 
  330:     if ($checked) {
  331:         $Str .= ' checked="checked"';
  332:     }
  333:     $Str .= ' />';
  334:     return $Str;
  335: }
  336: 
  337: 
  338: =pod
  339: 
  340: =item radiobutton
  341: 
  342: =cut
  343: 
  344: ##############################################
  345: ##############################################
  346: sub radio {
  347:     my ($name,$checked,$value) = @_;
  348:     my $Str = '<input type="radio" name="'.$name.'" ';
  349:     if (defined($value)) {
  350:         $Str .= 'value="'.$value.'"';
  351:     } 
  352:     if ($checked eq $value) {
  353:         $Str .= ' checked="checked"';
  354:     }
  355:     $Str .= ' />';
  356:     return $Str;
  357: }
  358: 
  359: ##############################################
  360: ##############################################
  361: 
  362: =pod
  363: 
  364: =item &date_setter
  365: 
  366: &date_setter returns html and javascript for a compact date-setting form.
  367: To retrieve values from it, use &get_date_from_form().
  368: 
  369: Inputs
  370: 
  371: =over 4
  372: 
  373: =item $dname 
  374: 
  375: The name to prepend to the form elements.  
  376: The form elements defined will be dname_year, dname_month, dname_day,
  377: dname_hour, dname_min, and dname_sec.
  378: 
  379: =item $currentvalue
  380: 
  381: The current setting for this time parameter.  A unix format time
  382: (time in seconds since the beginning of Jan 1st, 1970, GMT.  
  383: An undefined value is taken to indicate the value is the current time
  384: unless it is requested to leave it empty. See $includeempty.
  385: Also, to be explicit, a value of 'now' also indicates the current time.
  386: 
  387: =item $special
  388: 
  389: Additional html/javascript to be associated with each element in
  390: the date_setter.  See lonparmset for example usage.
  391: 
  392: =item $includeempty 
  393: 
  394: If it is set (true) and no date/time value is provided,
  395: the date/time fields are left empty.
  396: 
  397: =item $state
  398: 
  399: Specifies the initial state of the form elements.  Either 'disabled' or empty.
  400: Defaults to empty, which indiciates the form elements are not disabled. 
  401: 
  402: =back
  403: 
  404: Bugs
  405: 
  406: The method used to restrict user input will fail in the year 2400.
  407: 
  408: =cut
  409: 
  410: ##############################################
  411: ##############################################
  412: sub date_setter {
  413:     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
  414:         $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
  415:     my $now = time;
  416: 
  417:     my $tzname;
  418:     my ($sec,$min,$hour,$mday,$month,$year) = ('', '', undef,''.''.'');
  419:     #other potentially useful values:    wkday,yrday,is_daylight_savings
  420: 
  421:     if (! defined($state) || $state ne 'disabled') {
  422:         $state = '';
  423:     }
  424:     if (! defined($no_hh_mm_ss)) {
  425:         $no_hh_mm_ss = 0;
  426:     }
  427:     if ($currentvalue eq 'now') {
  428:         $currentvalue = $now;
  429:     }
  430:     
  431:     # Default value: Set empty date field to current time
  432:     # unless empty inclusion is requested
  433:     if ((!$includeempty) && (!$currentvalue)) {
  434:         $currentvalue = $now;
  435:     }
  436:     # Do we have a date? Split it!
  437:     if ($currentvalue) {
  438: 	($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue);
  439: 
  440:         #No values provided for hour, min, sec? Use default 0
  441:         if (($defhour) || ($defmin) || ($defsec)) {
  442:             $sec  = ($defsec  ? $defsec  : 0);
  443:             $min  = ($defmin  ? $defmin  : 0);
  444:             $hour = ($defhour ? $defhour : 0);
  445:         }
  446:     }
  447:     my $result = "\n<!-- $dname date setting form -->\n";
  448:     $result .= <<ENDJS;
  449: <script type="text/javascript">
  450: // <![CDATA[
  451:     function $dname\_checkday() {
  452:         var day   = document.$formname.$dname\_day.value;
  453:         var month = document.$formname.$dname\_month.value;
  454:         var year  = document.$formname.$dname\_year.value;
  455:         var valid = true;
  456:         if (day < 1) {
  457:             document.$formname.$dname\_day.value = 1;
  458:         } 
  459:         if (day > 31) {
  460:             document.$formname.$dname\_day.value = 31;
  461:         }
  462:         if ((month == 1)  || (month == 3)  || (month == 5)  ||
  463:             (month == 7)  || (month == 8)  || (month == 10) ||
  464:             (month == 12)) {
  465:             if (day > 31) {
  466:                 document.$formname.$dname\_day.value = 31;
  467:                 day = 31;
  468:             }
  469:         } else if (month == 2 ) {
  470:             if ((year % 4 == 0) && (year % 100 != 0)) {
  471:                 if (day > 29) {
  472:                     document.$formname.$dname\_day.value = 29;
  473:                 }
  474:             } else if (day > 29) {
  475:                 document.$formname.$dname\_day.value = 28;
  476:             }
  477:         } else if (day > 30) {
  478:             document.$formname.$dname\_day.value = 30;
  479:         }
  480:     }
  481:     
  482:     function $dname\_disable() {
  483:         document.$formname.$dname\_month.disabled=true;
  484:         document.$formname.$dname\_day.disabled=true;
  485:         document.$formname.$dname\_year.disabled=true;
  486:         document.$formname.$dname\_hour.disabled=true;
  487:         document.$formname.$dname\_minute.disabled=true;
  488:         document.$formname.$dname\_second.disabled=true;
  489:     }
  490: 
  491:     function $dname\_enable() {
  492:         document.$formname.$dname\_month.disabled=false;
  493:         document.$formname.$dname\_day.disabled=false;
  494:         document.$formname.$dname\_year.disabled=false;
  495:         document.$formname.$dname\_hour.disabled=false;
  496:         document.$formname.$dname\_minute.disabled=false;
  497:         document.$formname.$dname\_second.disabled=false;        
  498:     }
  499: 
  500:     function $dname\_opencalendar() {
  501:         if (! document.$formname.$dname\_month.disabled) {
  502:             var calwin=window.open(
  503: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
  504: document.$formname.$dname\_month.value+"&year="+
  505: document.$formname.$dname\_year.value,
  506:              "LONCAPAcal",
  507:               "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
  508:         }
  509: 
  510:     }
  511: // ]]>
  512: </script>
  513: ENDJS
  514:     $result .= '  <span class="LC_nobreak">';
  515:     my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
  516:     # Month
  517:     my @Months = qw/January February  March     April   May      June 
  518:                     July    August    September October November December/;
  519:     # Pad @Months with a bogus value to make indexing easier
  520:     unshift(@Months,'If you can read this an error occurred');
  521:     if ($includeempty) { $monthselector.="<option value=''></option>"; }
  522:     for(my $m = 1;$m <=$#Months;$m++) {
  523:         $monthselector .= qq{      <option value="$m"};
  524:         $monthselector .= ' selected="selected"' if ($m-1 eq $month);
  525:         $monthselector .= '> '.&mt($Months[$m]).' </option>'."\n";
  526:     }
  527:     $monthselector.= '  </select>';
  528:     # Day
  529:     my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
  530:     # Year
  531:     my $yearselector = qq{<input type="text" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
  532:     #
  533:     my $hourselector = qq{<select name="$dname\_hour" $special $state >};
  534:     if ($includeempty) { 
  535:         $hourselector.=qq{<option value=''></option>};
  536:     }
  537:     for (my $h = 0;$h<24;$h++) {
  538:         $hourselector .= qq{<option value="$h"};
  539:         $hourselector .= ' selected="selected"' if (defined($hour) && $hour == $h);
  540:         $hourselector .= ">";
  541:         my $timest='';
  542:         if ($h == 0) {
  543:             $timest .= "12 am";
  544:         } elsif($h == 12) {
  545:             $timest .= "12 noon";
  546:         } elsif($h < 12) {
  547:             $timest .= "$h am";
  548:         } else {
  549:             $timest .= $h-12 ." pm";
  550:         }
  551:         $timest=&mt($timest);
  552:         $hourselector .= $timest." </option>\n";
  553:     }
  554:     $hourselector .= "  </select>\n";
  555:     my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
  556:     my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
  557:     my $cal_link;
  558:     if (!$nolink) {
  559:         $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
  560:     }
  561:     #
  562:     my $tzone = ' '.$tzname.' ';
  563:     if ($no_hh_mm_ss) {
  564:         $result .= &mt('[_1] [_2] [_3] ',
  565:                        $monthselector,$dayselector,$yearselector).
  566:                    $tzone;
  567:         if (!$nolink) {
  568:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  569:         }
  570:     } else {
  571:         $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
  572:                       $monthselector,$dayselector,$yearselector,
  573:                       $hourselector,$minuteselector,$secondselector).
  574:                    $tzone;
  575:         if (!$nolink) {
  576:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  577:         }
  578:     }
  579:     $result .= "</span>\n<!-- end $dname date setting form -->\n";
  580:     return $result;
  581: }
  582: 
  583: sub get_timedates {
  584:     my ($epoch) = @_;
  585:     my $dt = DateTime->from_epoch(epoch => $epoch)
  586:                      ->set_time_zone(&Apache::lonlocal::gettimezone());
  587:     my $tzname = $dt->time_zone_short_name();
  588:     my $sec = $dt->second;
  589:     my $min = $dt->minute;
  590:     my $hour = $dt->hour;
  591:     my $mday = $dt->day;
  592:     my $month = $dt->month;
  593:     if ($month) {
  594:         $month --;
  595:     }
  596:     my $year = $dt->year;
  597:     return ($tzname,$sec,$min,$hour,$mday,$month,$year);
  598: }
  599: 
  600: sub build_url {
  601:     my ($base, $fields)=@_;
  602:     my $url;
  603:     $url = $base.'?';
  604:     foreach my $key (keys(%$fields)) {
  605:         $url.=&escape($key).'='.&escape($$fields{$key}).'&amp;';
  606:     }
  607:     $url =~ s/&amp;$//;
  608:     return $url;
  609: }
  610: 
  611: 
  612: ##############################################
  613: ##############################################
  614: 
  615: =pod
  616: 
  617: =item &get_date_from_form
  618: 
  619: get_date_from_form retrieves the date specified in an &date_setter form.
  620: 
  621: Inputs:
  622: 
  623: =over 4
  624: 
  625: =item $dname
  626: 
  627: The name passed to &date_setter, which prefixes the form elements.
  628: 
  629: =item $defaulttime
  630: 
  631: The unix time to use as the default in case of poor inputs.
  632: 
  633: =back
  634: 
  635: Returns: Unix time represented in the form.
  636: 
  637: =cut
  638: 
  639: ##############################################
  640: ##############################################
  641: sub get_date_from_form {
  642:     my ($dname) = @_;
  643:     my ($sec,$min,$hour,$day,$month,$year);
  644:     #
  645:     if (defined($env{'form.'.$dname.'_second'})) {
  646:         my $tmpsec = $env{'form.'.$dname.'_second'};
  647:         if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
  648:             $sec = $tmpsec;
  649:         }
  650: 	if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
  651:     } else {
  652:         $sec = 0;
  653:     }
  654:     if (defined($env{'form.'.$dname.'_minute'})) {
  655:         my $tmpmin = $env{'form.'.$dname.'_minute'};
  656:         if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
  657:             $min = $tmpmin;
  658:         }
  659: 	if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
  660:     } else {
  661:         $min = 0;
  662:     }
  663:     if (defined($env{'form.'.$dname.'_hour'})) {
  664:         my $tmphour = $env{'form.'.$dname.'_hour'};
  665:         if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
  666:             $hour = $tmphour;
  667:         }
  668:     } else {
  669:         $hour = 0;
  670:     }
  671:     if (defined($env{'form.'.$dname.'_day'})) {
  672:         my $tmpday = $env{'form.'.$dname.'_day'};
  673:         if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
  674:             $day = $tmpday;
  675:         }
  676:     }
  677:     if (defined($env{'form.'.$dname.'_month'})) {
  678:         my $tmpmonth = $env{'form.'.$dname.'_month'};
  679:         if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
  680:             $month = $tmpmonth;
  681:         }
  682:     }
  683:     if (defined($env{'form.'.$dname.'_year'})) {
  684:         my $tmpyear = $env{'form.'.$dname.'_year'};
  685:         if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
  686:             $year = $tmpyear;
  687:         }
  688:     }
  689:     if (($year<1970) || ($year>2037)) { return undef; }
  690:     if (defined($sec) && defined($min)   && defined($hour) &&
  691:         defined($day) && defined($month) && defined($year)) {
  692:         my $timezone = &Apache::lonlocal::gettimezone();
  693:         my $dt = DateTime->new( year   => $year,
  694:                                 month  => $month,
  695:                                 day    => $day,
  696:                                 hour   => $hour,
  697:                                 minute => $min,
  698:                                 second => $sec,
  699:                                 time_zone => $timezone,
  700:                               );
  701:         my $epoch_time  = $dt->epoch;
  702:         if ($epoch_time ne '') {
  703:             return $epoch_time;
  704:         } else {
  705:             return undef;
  706:         }
  707:     } else {
  708:         return undef;
  709:     }
  710: }
  711: 
  712: ##############################################
  713: ##############################################
  714: 
  715: =pod
  716: 
  717: =item &pjump_javascript_definition()
  718: 
  719: Returns javascript defining the 'pjump' function, which opens up a
  720: parameter setting wizard.
  721: 
  722: =cut
  723: 
  724: ##############################################
  725: ##############################################
  726: sub pjump_javascript_definition {
  727:     my $Str = <<END;
  728:     function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
  729:         parmwin=window.open("/adm/rat/parameter.html?type="+escape(type)
  730:                  +"&value="+escape(value)+"&marker="+escape(marker)
  731:                  +"&return="+escape(ret)
  732:                  +"&call="+escape(call)+"&name="+escape(dis)
  733:                  +"&defhour="+escape(hour)+"&defmin="+escape(min)
  734:                  +"&defsec="+escape(sec),"LONCAPAparms",
  735:                  "height=350,width=350,scrollbars=no,menubar=no");
  736:     }
  737: END
  738:     return $Str;
  739: }
  740: 
  741: ##############################################
  742: ##############################################
  743: 
  744: =pod
  745: 
  746: =item &javascript_nothing()
  747: 
  748: Return an appropriate null for the users browser.  This is used
  749: as the first arguement for window.open calls when you want a blank
  750: window that you can then write to.
  751: 
  752: =cut
  753: 
  754: ##############################################
  755: ##############################################
  756: sub javascript_nothing {
  757:     # mozilla and other browsers work with "''", but IE on mac does not.
  758:     my $nothing = "''";
  759:     my $user_browser;
  760:     my $user_os;
  761:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  762:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  763:     if (! defined($user_browser) || ! defined($user_os)) {
  764:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  765:                            &Apache::loncommon::decode_user_agent();
  766:     }
  767:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
  768:         $nothing = "'javascript:void(0);'";
  769:     }
  770:     return $nothing;
  771: }
  772: 
  773: ##############################################
  774: ##############################################
  775: sub javascript_docopen {
  776:     my ($mimetype) = @_;
  777:     $mimetype ||= 'text/html';
  778:     # safari does not understand document.open() and loads "text/html"
  779:     my $nothing = "''";
  780:     my $user_browser;
  781:     my $user_os;
  782:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  783:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  784:     if (! defined($user_browser) || ! defined($user_os)) {
  785:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  786:                            &Apache::loncommon::decode_user_agent();
  787:     }
  788:     if ($user_browser eq 'safari' && $user_os =~ 'mac') {
  789:         $nothing = "document.clear()";
  790:     } else {
  791: 	$nothing = "document.open('$mimetype','replace')";
  792:     }
  793:     return $nothing;
  794: }
  795: 
  796: 
  797: ##############################################
  798: ##############################################
  799: 
  800: =pod
  801: 
  802: =item &StatusOptions()
  803: 
  804: Returns html for a selection box which allows the user to choose the
  805: enrollment status of students.  The selection box name is 'Status'.
  806: 
  807: Inputs:
  808: 
  809: $status: the currently selected status.  If undefined the value of
  810: $env{'form.Status'} is taken.  If that is undefined, a value of 'Active'
  811: is used.
  812: 
  813: $formname: The name of the form.  If defined the onchange attribute of
  814: the selection box is set to document.$formname.submit().
  815: 
  816: $size: the size (number of lines) of the selection box.
  817: 
  818: $onchange: javascript to use when the value is changed.  Enclosed in 
  819: double quotes, ""s, not single quotes.
  820: 
  821: Returns: a perl string as described.
  822: 
  823: =cut
  824: 
  825: ##############################################
  826: ##############################################
  827: sub StatusOptions {
  828:     my ($status, $formName,$size,$onchange,$mult)=@_;
  829:     $size = 1 if (!defined($size));
  830:     if (! defined($status)) {
  831:         $status = 'Active';
  832:         $status = $env{'form.Status'} if (exists($env{'form.Status'}));
  833:     }
  834: 
  835:     my $Str = '';
  836:     $Str .= '<select name="Status"';
  837:     if (defined($mult)){
  838:         $Str .= ' multiple="multiple" ';
  839:     }
  840:     if(defined($formName) && $formName ne '' && ! defined($onchange)) {
  841:         $Str .= ' onchange="document.'.$formName.'.submit()"';
  842:     }
  843:     if (defined($onchange)) {
  844:         $Str .= ' onchange="'.$onchange.'"';
  845:     }
  846:     $Str .= ' size="'.$size.'" ';
  847:     $Str .= '>'."\n";
  848:     foreach my $type (['Active',  &mt('Currently Has Access')],
  849: 		      ['Future',  &mt('Will Have Future Access')],
  850: 		      ['Expired', &mt('Previously Had Access')],
  851: 		      ['Any',     &mt('Any Access Status')]) {
  852: 	my ($name,$label) = @$type;
  853: 	$Str .= '<option value="'.$name.'" ';
  854: 	if ($status eq $name) {
  855: 	    $Str .= 'selected="selected" ';
  856: 	}
  857: 	$Str .= '>'.$label.'</option>'."\n";
  858:     }
  859: 
  860:     $Str .= '</select>'."\n";
  861: }
  862: 
  863: ########################################################
  864: ########################################################
  865: 
  866: =pod
  867: 
  868: =item Progess Window Handling Routines
  869: 
  870: These routines handle the creation, update, increment, and closure of 
  871: progress windows.  The progress window reports to the user the number
  872: of items completed and an estimate of the time required to complete the rest.
  873: 
  874: =over 4
  875: 
  876: 
  877: =item &Create_PrgWin
  878: 
  879: Writes javascript to the client to open a progress window and returns a
  880: data structure used for bookkeeping.
  881: 
  882: Inputs
  883: 
  884: =over 4
  885: 
  886: =item $r Apache request
  887: 
  888: =item $title The title of the progress window
  889: 
  890: =item $heading A description (usually 1 line) of the process being initiated.
  891: 
  892: =item $number_to_do The total number of items being processed.
  893: 
  894: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
  895:        specified)
  896: 
  897: =item $width Specify the width in charaters of the input field.
  898: 
  899: =item $formname Only useful in the inline case, if a form already exists, this needs to be used and specfiy the name of the form, otherwise the Progress line will be created in a new form of it's own
  900: 
  901: =item $inputname Only useful in the inline case, if a form and an input of type text exists, use this to specify the name of the input field 
  902: 
  903: =back
  904: 
  905: Returns a hash containing the progress state data structure.
  906: 
  907: 
  908: =item &Update_PrgWin
  909: 
  910: Updates the text in the progress indicator.  Does not increment the count.
  911: See &Increment_PrgWin.
  912: 
  913: Inputs:
  914: 
  915: =over 4
  916: 
  917: =item $r Apache request
  918: 
  919: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
  920: 
  921: =item $displaystring The string to write to the status indicator
  922: 
  923: =back
  924: 
  925: Returns: none
  926: 
  927: 
  928: =item Increment_PrgWin
  929: 
  930: Increment the count of items completed for the progress window by $step or 1 if no step is provided.
  931: 
  932: Inputs:
  933: 
  934: =over 4
  935: 
  936: =item $r Apache request
  937: 
  938: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  939: 
  940: =item $extraInfo A description of the items being iterated over.  Typically
  941: 'student'.
  942: 
  943: =item $step (optional) counter step. Will be set to default 1 if ommited. step must be greater than 0 or empty.
  944: 
  945: =back
  946: 
  947: Returns: none
  948: 
  949: 
  950: =item Close_PrgWin
  951: 
  952: Closes the progress window.
  953: 
  954: Inputs:
  955: 
  956: =over 4 
  957: 
  958: =item $r Apache request
  959: 
  960: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  961: 
  962: =back
  963: 
  964: Returns: none
  965: 
  966: =back
  967: 
  968: =cut
  969: 
  970: ########################################################
  971: ########################################################
  972: 
  973: my $uniq=0;
  974: sub get_uniq_name {
  975:     $uniq++;
  976:     return 'uniquename'.$uniq;
  977: }
  978: 
  979: # Create progress
  980: sub Create_PrgWin {
  981:     my ($r, $title, $heading, $number_to_do,$type,$width,$formname,
  982: 	$inputname)=@_;
  983:     if (!defined($type)) { $type='popup'; }
  984:     if (!defined($width)) { $width=55; }
  985:     my %prog_state;
  986:     $prog_state{'type'}=$type;
  987:     if ($type eq 'popup') {
  988: 	$prog_state{'window'}='popwin';
  989: 	my $start_page =
  990: 	    &Apache::loncommon::start_page($title,undef,
  991: 					   {'only_body' => 1,
  992: 					    'bgcolor'   => '#88DDFF',
  993: 					    'js_ready'  => 1});
  994: 	my $end_page = &Apache::loncommon::end_page({'js_ready'  => 1});
  995: 
  996: 	#the whole function called through timeout is due to issues
  997: 	#in mozilla Read BUG #2665 if you want to know the whole story
  998: 	&r_print($r,&Apache::lonhtmlcommon::scripttag(
  999:         "var popwin;
 1000:          function openpopwin () {
 1001:          popwin=open(\'\',\'popwin\',\'width=400,height=100\');".
 1002:         "popwin.document.writeln(\'".$start_page.
 1003:               "<h4>".&mt("$heading")."<\/h4>".
 1004:               "<form action=\"\" name=\"popremain\" method=\"post\">".
 1005:               '<input type="text" size="'.$width.'" name="remaining" value="'.
 1006: 	      &mt('Starting').'" /><\\/form>'.$end_page.
 1007:               "\');".
 1008:         "popwin.document.close();}".
 1009:         "\nwindow.setTimeout(openpopwin,0)"
 1010:     ));
 1011: 	$prog_state{'formname'}='popremain';
 1012: 	$prog_state{'inputname'}="remaining";
 1013:     } elsif ($type eq 'inline') {
 1014: 	$prog_state{'window'}='window';
 1015: 	if (!$formname) {
 1016: 	    $prog_state{'formname'}=&get_uniq_name();
 1017: 	    &r_print($r,'<form action="" name="'.$prog_state{'formname'}.'">');
 1018: 	} else {
 1019: 	    $prog_state{'formname'}=$formname;
 1020: 	}
 1021: 	if (!$inputname) {
 1022: 	    $prog_state{'inputname'}=&get_uniq_name();
 1023: 	    &r_print($r,&mt("$heading [_1]",' <input type="text" name="'.$prog_state{'inputname'}.'" size="'.$width.'" />'));
 1024: 	} else {
 1025: 	    $prog_state{'inputname'}=$inputname;
 1026: 	    
 1027: 	}
 1028: 	if (!$formname) { &r_print($r,'</form>'); }
 1029: 	&Update_PrgWin($r,\%prog_state,&mt('Starting'));
 1030:     }
 1031: 
 1032:     $prog_state{'done'}=0;
 1033:     $prog_state{'firststart'}=&Time::HiRes::time();
 1034:     $prog_state{'laststart'}=&Time::HiRes::time();
 1035:     $prog_state{'max'}=$number_to_do;
 1036:     
 1037:     return %prog_state;
 1038: }
 1039: 
 1040: # update progress
 1041: sub Update_PrgWin {
 1042:     my ($r,$prog_state,$displayString)=@_;
 1043:     &r_print($r,&Apache::lonhtmlcommon::scripttag(
 1044:         $$prog_state{'window'}.'.document.'.
 1045:         $$prog_state{'formname'}.'.'.
 1046:         $$prog_state{'inputname'}.'.value="'.
 1047:         $displayString.'";'
 1048:     ));
 1049:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1050: }
 1051: 
 1052: # increment progress state
 1053: sub Increment_PrgWin {
 1054:     my ($r,$prog_state,$extraInfo,$step)=@_;
 1055:     $step = $step > 0 ? $step : 1;
 1056:     $$prog_state{'done'} += $step;
 1057: 
 1058:     # Catch (max modulo step) <> 0
 1059:     my $current = $$prog_state{'done'};
 1060:     my $last = ($$prog_state{'max'} - $current);
 1061:     if ($last <= 0) {
 1062:         $last = 1;
 1063:         $current = $$prog_state{'max'};
 1064:     }
 1065: 
 1066:     my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
 1067:         $current * $last;
 1068:     $time_est = int($time_est);
 1069:     #
 1070:     my $min = int($time_est/60);
 1071:     my $sec = $time_est % 60;
 1072: 
 1073:     my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
 1074:     if ($lasttime > 9) {
 1075:         $lasttime = int($lasttime);
 1076:     } elsif ($lasttime < 0.01) {
 1077:         $lasttime = 0;
 1078:     } else {
 1079:         $lasttime = sprintf("%3.2f",$lasttime);
 1080:     }
 1081: 
 1082:     $sec = 0 if ($min >= 10); # Don't show seconds if remaining time >= 10 min.
 1083:     $sec = 1 if ( ($min == 0) && ($sec == 0) ); # Little cheating: pretend to have 1 second remaining instead of 0 to have something to display
 1084: 
 1085:     my $timeinfo =
 1086:         &mt('[_1]/[_2]:'
 1087:            .' [quant,_3,minute,minutes,] [quant,_4,second ,seconds ,]remaining'
 1088:            .' ([quant,_5,second] for '.$extraInfo.')',
 1089:             $current,
 1090:             $$prog_state{'max'},
 1091:             $min,
 1092:             $sec,
 1093:             $lasttime);
 1094: 
 1095:     &r_print($r,&Apache::lonhtmlcommon::scripttag(
 1096:         $$prog_state{'window'}.'.document.'.
 1097:         $$prog_state{'formname'}.'.'.
 1098:         $$prog_state{'inputname'}.'.value="'.$timeinfo.'";'
 1099:     ));
 1100:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1101: }
 1102: 
 1103: # close Progress Line
 1104: sub Close_PrgWin {
 1105:     my ($r,$prog_state)=@_;
 1106:     if ($$prog_state{'type'} eq 'popup') {
 1107:         &r_print($r,&Apache::lonhtmlcommon::scripttag(
 1108:             'popwin.close()'
 1109:         ));
 1110:     } elsif ($$prog_state{'type'} eq 'inline') {
 1111: 	&Update_PrgWin($r,$prog_state,&mt('Done'));
 1112:     }
 1113:     undef(%$prog_state);
 1114: }
 1115: 
 1116: sub r_print {
 1117:     my ($r,$to_print)=@_;
 1118:     if ($r) {
 1119: 	$r->print($to_print);
 1120: 	$r->rflush();
 1121:     } else {
 1122: 	print($to_print);
 1123:     }
 1124: }
 1125: 
 1126: # ------------------------------------------------------- Puts directory header
 1127: 
 1128: sub crumbs {
 1129:     my ($uri,$target,$prefix,$form,$skiplast)=@_;
 1130:     if ($target) {
 1131:         $target = ' target="'.
 1132:                   &Apache::loncommon::escape_single($target).'"';
 1133:     }
 1134:     my $output='<span class="LC_filename">';
 1135:     $output.=$prefix.'/';
 1136:     if (($env{'user.adv'}) || ($env{'user.author'})) {
 1137:         my $path=$prefix.'/';
 1138:         foreach my $dir (split('/',$uri)) {
 1139:             if (! $dir) { next; }
 1140:             $path .= $dir;
 1141:             if ($path eq $uri) {
 1142:                 if ($skiplast) {
 1143:                     $output.=$dir;
 1144:                     last;
 1145:                 } 
 1146:             } else {
 1147:                 $path.='/'; 
 1148:             }
 1149:             my $href_path = &HTML::Entities::encode($path,'<>&"');
 1150:             &Apache::loncommon::inhibit_menu_check(\$href_path);
 1151:             if ($form) {
 1152:                 my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
 1153:                 $output.=qq{<a href="$href"$target>$dir</a>/};
 1154:             } else {
 1155:                 $output.=qq{<a href="$href_path"$target>$dir</a>/};
 1156:             }
 1157:         }
 1158:     } else {
 1159:         foreach my $dir (split('/',$uri)) {
 1160:             if (! $dir) { next; }
 1161:             $output.=$dir.'/';
 1162:         }
 1163:     }
 1164:     if ($uri !~ m|/$|) { $output=~s|/$||; }
 1165:     $output.='</span>';
 1166: 
 1167:     return $output;
 1168: }
 1169: 
 1170: # --------------------- A function that generates a window for the spellchecker
 1171: 
 1172: sub spellheader {
 1173:     my $start_page=
 1174: 	&Apache::loncommon::start_page('Speller Suggestions',undef,
 1175: 				       {'only_body'   => 1,
 1176: 					'js_ready'    => 1,
 1177: 					'bgcolor'     => '#DDDDDD',
 1178: 				        'add_entries' => {
 1179: 					    'onload' => 
 1180:                                                'document.forms.spellcheckform.submit()',
 1181:                                              }
 1182: 				        });
 1183:     my $end_page=
 1184: 	&Apache::loncommon::end_page({'js_ready'  => 1}); 
 1185: 
 1186:     my $nothing=&javascript_nothing();
 1187:     return (<<ENDCHECK);
 1188: <script type="text/javascript"> 
 1189: // <![CDATA[
 1190: //<!-- BEGIN LON-CAPA Internal
 1191: var checkwin;
 1192: 
 1193: function spellcheckerwindow(string) {
 1194:     var esc_string = string.replace(/\"/g,'&quot;');
 1195:     checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
 1196:     checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
 1197:     checkwin.document.close();
 1198: }
 1199: // END LON-CAPA Internal -->
 1200: // ]]>
 1201: </script>
 1202: ENDCHECK
 1203: }
 1204: 
 1205: # ---------------------------------- Generate link to spell checker for a field
 1206: 
 1207: sub spelllink {
 1208:     my ($form,$field)=@_;
 1209:     my $linktext=&mt('Check Spelling');
 1210:     return (<<ENDLINK);
 1211: <a href="javascript:if (typeof(document.$form.onsubmit)!='undefined') { if (document.$form.onsubmit!=null) { document.$form.onsubmit();}};spellcheckerwindow(this.document.forms.$form.$field.value);">$linktext</a>
 1212: ENDLINK
 1213: }
 1214: 
 1215: # ------------------------------------------------- Output headers for CKEditor
 1216: 
 1217: sub htmlareaheaders {
 1218: 	my $s="";
 1219: 	if (&htmlareabrowser()) {
 1220: 		$s.=(<<ENDEDITOR);
 1221: <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
 1222: ENDEDITOR
 1223: 	}
 1224:     $s.=(<<ENDJQUERY);
 1225: <script type="text/javascript" src="/adm/jQuery/js/jquery-1.3.2.min.js"></script>
 1226: <script type="text/javascript" src="/adm/jQuery/js/jquery-ui-1.7.2.custom.min.js"></script>
 1227: <link rel="stylesheet" type="text/css" href="/adm/jQuery/css/smoothness/jquery-ui-1.7.2.custom.css" />
 1228: ENDJQUERY
 1229: 	return $s;
 1230: }
 1231: 
 1232: # ----------------------------------------------------------------- Preferences
 1233: 
 1234: # ------------------------------------------------- lang to use in html editor
 1235: sub htmlarea_lang {
 1236:     my $lang='en';
 1237:     if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
 1238: 	$lang=&mt('htmlarea_lang');
 1239:     }
 1240:     return $lang;
 1241: }
 1242: 
 1243: # ----------------------------------------- Script to activate only some fields
 1244: 
 1245: sub htmlareaselectactive {
 1246:     my ($args) = @_; 
 1247:     unless (&htmlareabrowser()) { return ''; }
 1248:     my $output='<script type="text/javascript" defer="defer">'."\n"
 1249:               .'// <![CDATA['."\n";
 1250:     my $lang = &htmlarea_lang();
 1251:     my $fullpage = 'false';
 1252:     my ($dragmath_prefix,$dragmath_helpicon,$dragmath_whitespace);
 1253:     if (ref($args) eq 'HASH') {
 1254:         if (exists($args->{'lang'})) {
 1255:             if ($args->{'lang'} ne '') {
 1256:                 $lang = $args->{'lang'};
 1257:             }
 1258:         }
 1259:         if (exists($args->{'fullpage'})) { 
 1260:             if ($args->{'fullpage'} eq 'true') {
 1261:                 $fullpage = $args->{'fullpage'};
 1262:             }
 1263:         }
 1264:         if (exists($args->{'dragmath'})) {
 1265:             if ($args->{'dragmath'} ne '') {
 1266:                 $dragmath_prefix = $args->{'dragmath'};
 1267:                 $dragmath_helpicon=&Apache::loncommon::lonhttpdurl("/adm/help/help.png");
 1268:                 $dragmath_whitespace=&Apache::loncommon::lonhttpdurl("/adm/lonIcons/transparent1x1.gif");
 1269:             }
 1270:         }
 1271:     }
 1272:     $output.='
 1273:     
 1274:     function containsBlockHtml(id) {
 1275: 		var re = $("#"+id).html().search(/(?:\&lt\;|\<)(br|h1|h2|h3|h4|h5|h6|p|ol|ul|table|pre|address|blockquote|center|div)[\s]*((?:[\/]*[\s]*(?:\&gt\;|\>)|(?:\&gt\;|\>)[\s\S]*(?:\&lt\;|\<)\/[\s]*\1[\s]*\(?:\&gt\;|\>))/im);
 1276:     	return (re >= 0);
 1277:     }
 1278:     
 1279:     function startRichEditor(id) {
 1280:     	CKEDITOR.replace(id, 
 1281:     		{
 1282:     			customConfig: "/ckeditor/loncapaconfig.js",
 1283:                         language : "'.$lang.'",
 1284:                         fullPage : '.$fullpage.',
 1285:     		}
 1286:     	);
 1287:     }
 1288:     
 1289:     function destroyRichEditor(id) {
 1290:     	CKEDITOR.instances[id].destroy();
 1291:     }
 1292:     
 1293:     function editorHandler(event) {
 1294:     	var rawid = $(this).attr("id");
 1295:     	var id = new RegExp("LC_rt_(.*)").exec(rawid)[1];
 1296:     	event.preventDefault();
 1297:     	var rt_enabled  = $(this).hasClass("LC_enable_rt");
 1298:         if (rt_enabled) {
 1299:     		startRichEditor(id);
 1300: 			$("#LC_rt_"+id).html("<b>&laquo; Plain text</b>");
 1301: 			$("#LC_rt_"+id).attr("title", "Disable rich text formatting and edit in plain text");
 1302: 			$("#LC_rt_"+id).addClass("LC_disable_rt");
 1303: 			$("#LC_rt_"+id).removeClass("LC_enable_rt");
 1304:     	} else {
 1305: 			destroyRichEditor(id);
 1306: 			$("#LC_rt_"+id).html("<b>Rich formatting &raquo;</b>");
 1307: 			$("#LC_rt_"+id).attr("title", "Enable rich text formatting (bold, italic, etc.)");
 1308: 			$("#LC_rt_"+id).addClass("LC_enable_rt");
 1309: 			$("#LC_rt_"+id).removeClass("LC_disable_rt");
 1310: 	}';
 1311:     if ($dragmath_prefix ne '') {
 1312:         $output .= "\n                 var visible = '';
 1313:                                        if (rt_enabled) {
 1314:                                            visible = 'none';
 1315:                                        }
 1316:                                        editmath_visibility(id,visible);\n";
 1317:     }
 1318:     $output .= '
 1319:     }
 1320:     $(document).ready(function(){
 1321: 		$(".LC_richAlwaysOn").each(function() {
 1322: 			startRichEditor($(this).attr("id"));
 1323: 		});
 1324: 		$(".LC_richDetectHtml").each(function() {
 1325: 			var id = $(this).attr("id");
 1326:                         var rt_enabled = containsBlockHtml(id);
 1327: 			if(rt_enabled) {
 1328: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>&laquo; Plain text</b></a></div>");				
 1329: 				startRichEditor(id);
 1330: 				$("#LC_rt_"+id).click(editorHandler);
 1331: 			}
 1332: 			else {
 1333: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting &raquo;</b></a></div>");
 1334: 				$("#LC_rt_"+id).click(editorHandler);
 1335: 			}';
 1336:     if ($dragmath_prefix ne '') {
 1337:         $output .= "\n                 var visible = '';
 1338:                                        if (rt_enabled) {
 1339:                                            visible = 'none';
 1340:                                        }
 1341:                                        editmath_visibility(id,visible);\n";
 1342:     }
 1343:     $output .= '
 1344: 		});
 1345: 		$(".LC_richDefaultOn").each(function() {
 1346: 			var id = $(this).attr("id");
 1347: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Disable rich text formatting and edit in plain text\" class=\"LC_disable_rt\"><b>&laquo; Plain text</b></a></div>");				
 1348: 			startRichEditor(id);
 1349: 			$("#LC_rt_"+id).click(editorHandler);
 1350: 		});
 1351: 		$(".LC_richDefaultOff").each(function() {
 1352: 			var id = $(this).attr("id");
 1353: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"Enable rich text formatting (bold, italic, etc.)\" class=\"LC_enable_rt\"><b>Rich formatting &raquo;</b></a></div>");
 1354: 			$("#LC_rt_"+id).click(editorHandler);
 1355: 		});
 1356: 	});
 1357: ';
 1358:     if ($dragmath_prefix ne '') {
 1359:         $output .= '
 1360: 
 1361:      function editmath_visibility(id,value) {
 1362: 
 1363:          if ((id == "") || (id == null)) {
 1364:              return;
 1365:          }
 1366:          var mathid = "'.$dragmath_prefix.'_"+id;
 1367:          mathele = document.getElementById(mathid);
 1368:          if (mathele == null) {
 1369:              return;
 1370:          }
 1371:          mathele.style.display = value;
 1372:          var mathhelpicon = "'.$dragmath_prefix.'helpicon'.'_"+id;
 1373:          mathhelpiconele = document.getElementById(mathhelpicon);
 1374:          if (mathhelpiconele == null) {
 1375:              return;
 1376:          }
 1377:          if (value == "none") {
 1378:              mathhelpiconele.src = "'.$dragmath_whitespace.'";
 1379:          } else {
 1380:              mathhelpiconele.src = "'.$dragmath_helpicon.'";
 1381:          }
 1382:      }
 1383: ';
 1384: 
 1385:     }
 1386:     $output.="\nwindow.status='Activated Editfields';\n"
 1387:             .'// ]]>'."\n"
 1388:             .'</script>';
 1389:     return $output;
 1390: }
 1391: 
 1392: # --------------------------------------------------------------------- Blocked
 1393: 
 1394: sub htmlareablocked {
 1395:     unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
 1396:     return 0;
 1397: }
 1398: 
 1399: # ---------------------------------------- Browser capable of running HTMLArea?
 1400: 
 1401: sub htmlareabrowser {
 1402:     return 1;
 1403: }
 1404: 
 1405: ############################################################
 1406: ############################################################
 1407: 
 1408: =pod
 1409: 
 1410: =item breadcrumbs
 1411: 
 1412: Compiles the previously registered breadcrumbs into an series of links.
 1413: Additionally supports a 'component', which will be displayed on the
 1414: right side of the breadcrumbs enclosing div (without a link).
 1415: A link to help for the component will be included if one is specified.
 1416: 
 1417: All inputs can be undef without problems.
 1418: 
 1419: Inputs: $component (the text on the right side of the breadcrumbs trail),
 1420:         $component_help
 1421:         $menulink (boolean, controls whether to include a link to /adm/menu)
 1422:         $helplink (if 'nohelp' don't include the orange help link)
 1423:         $css_class (optional name for the class to apply to the table for CSS)
 1424:         $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component
 1425:            when including the text on the right.
 1426: Returns a string containing breadcrumbs for the current page.
 1427: 
 1428: =item clear_breadcrumbs
 1429: 
 1430: Clears the previously stored breadcrumbs.
 1431: 
 1432: =item add_breadcrumb
 1433: 
 1434: Pushes a breadcrumb on the stack of crumbs.
 1435: 
 1436: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
 1437: are required.  If present the keys 'faq' and 'bug' will be used to provide
 1438: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' 
 1439: and 'text' values won't be sent through &mt()
 1440: 
 1441: returns: nothing    
 1442: 
 1443: =cut
 1444: 
 1445: ############################################################
 1446: ############################################################
 1447: {
 1448:     my @Crumbs;
 1449:     my %tools = ();
 1450:     
 1451:     sub breadcrumbs {
 1452:         my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, $CourseBreadcrumbs) = @_;
 1453:         #
 1454:         $css_class ||= 'LC_breadcrumbs';
 1455: 
 1456:         # Make the faq and bug data cascade
 1457:         my $faq  = '';
 1458:         my $bug  = '';
 1459:         my $help = '';
 1460:         # Crumb Symbol
 1461:         my $crumbsymbol = '&raquo;';
 1462:         # The last breadcrumb does not have a link, so handle it separately.
 1463:         my $last = pop(@Crumbs);
 1464:         #
 1465:         # The first one should be the course or a menu link
 1466:         if (!defined($menulink)) { $menulink=1; }
 1467:         if ($menulink) {
 1468:             my $description = 'Menu';
 1469:             my $no_mt_descr = 0;
 1470:             if ((exists($env{'request.course.id'})) && 
 1471:                 ($env{'request.course.id'} ne '') && 
 1472:                 ($env{'course.'.$env{'request.course.id'}.'.description'} ne '')) {
 1473:                 $description = 
 1474:                     $env{'course.'.$env{'request.course.id'}.'.description'};
 1475:                 $no_mt_descr = 1;
 1476:             }
 1477:             $menulink =  {  href   =>'/adm/menu',
 1478:                             title  =>'Go to main menu',
 1479:                             target =>'_top',
 1480:                             text   =>$description,
 1481:                             no_mt  =>$no_mt_descr, };
 1482:             if($last) {
 1483:                 #$last set, so we have some crumbs
 1484:                 unshift(@Crumbs,$menulink);
 1485:             } else {
 1486:                 #only menulink crumb present
 1487:                 $last = $menulink;
 1488:             }
 1489:         }
 1490:         my $links = join "", 
 1491:              map {
 1492:                  $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
 1493:                  $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
 1494:                  $help = $_->{'help'} if (exists($_->{'help'}));
 1495: 
 1496:                  my $result = $_->{no_mt} ? $_->{text} : mt($_->{text});
 1497: 
 1498:                  if ($_->{href}){
 1499:                      $result = htmltag( 'a', $result, 
 1500:                        { href   => $_->{href},
 1501:                          title  => $_->{no_mt} ? $_->{title} : mt($_->{title}),
 1502:                          target => $_->{target}, });
 1503:                  }
 1504: 
 1505:                  $result = htmltag( 'li', "$result $crumbsymbol");
 1506:              } @Crumbs;
 1507: 
 1508:         #should the last Element be translated?
 1509: 
 1510:         my $lasttext = $last->{'no_mt'} ? $last->{'text'} 
 1511:                      : mt( $last->{'text'} );
 1512: 
 1513:         # last breadcrumb is the first order heading of a page
 1514:         # for course breadcrumbs it's just bold
 1515:         $links .= htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
 1516:                 $lasttext), {title => $lasttext});
 1517: 
 1518:         my $icons = '';
 1519:         $faq  = $last->{'faq'}  if (exists($last->{'faq'}));
 1520:         $bug  = $last->{'bug'}  if (exists($last->{'bug'}));
 1521:         $help = $last->{'help'} if (exists($last->{'help'}));
 1522:         $component_help=($component_help?$component_help:$help);
 1523: #        if ($faq ne '') {
 1524: #            $icons .= &Apache::loncommon::help_open_faq($faq);
 1525: #        }
 1526: #        if ($bug ne '') {
 1527: #            $icons .= &Apache::loncommon::help_open_bug($bug);
 1528: #        }
 1529:         if ($faq ne '' || $component_help ne '' || $bug ne '') {
 1530:             $icons .= &Apache::loncommon::help_open_menu($component,
 1531:                                                          $component_help,
 1532:                                                          $faq,$bug);
 1533:         }
 1534:         #
 1535: 		
 1536: 
 1537:         unless ($CourseBreadcrumbs) {
 1538:             $links = htmltag('ol',  $links, { id => "LC_MenuBreadcrumbs"   });
 1539:         } else {
 1540:             $links = htmltag('ul',  $links, { class => "LC_CourseBreadcrumbs" });
 1541:         }
 1542: 
 1543:         if ($component) {
 1544:             $links = htmltag('span', 
 1545:                              ( $no_mt ? $component : mt($component) ).
 1546:                              ( $icons ? $icons : '' ),
 1547:                              { class => 'LC_breadcrumbs_component' } )
 1548:                              .$links;
 1549:         }
 1550:         
 1551:         render_tools(\$links);
 1552:         $links = htmltag('div', $links, 
 1553:                         { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ;
 1554:         render_advtools(\$links);
 1555: 
 1556:         # Return the @Crumbs stack to what we started with
 1557:         push(@Crumbs,$last);
 1558:         shift(@Crumbs);
 1559:         # Return the breadcrumb's line
 1560:         return "$links";
 1561:     }
 1562: 
 1563:     sub clear_breadcrumbs {
 1564:         undef(@Crumbs);
 1565:         undef(%tools);
 1566:     }
 1567: 
 1568:     sub add_breadcrumb {
 1569:         push(@Crumbs,@_);
 1570:     }
 1571:     
 1572: =item add_breadcrumb_tool($category, $html)
 1573: 
 1574: Adds $html to $category of the breadcrumb toolbar container.
 1575: 
 1576: $html is usually a link to a page that invokes a function on the currently 
 1577: displayed data (e.g. print when viewing a problem)
 1578: 
 1579: Currently there are 3 possible values for $category: 
 1580: 
 1581: =over 
 1582: 
 1583: =item navigation 
 1584: left of breadcrumbs line
 1585: 
 1586: =item tools 
 1587: right of breadcrumbs line
 1588: 
 1589: =item advtools 
 1590: advanced tools shown in a separate box below breadcrumbs line 
 1591: 
 1592: =back
 1593:  
 1594: returns: nothing
 1595: 
 1596: =cut
 1597: 
 1598:     sub add_breadcrumb_tool {
 1599:         my ($category, @html) = @_;
 1600:         return unless @html;
 1601:         if (!defined(%tools)) { 
 1602:             %tools = ( navigation => [], tools => [], advtools => []);
 1603:         }
 1604: 
 1605:         #this cleans data received from lonmenu::innerregister
 1606:         @html = grep {defined $_ && $_ ne ''} @html;
 1607:         for (@html) { 
 1608:             s/align="(right|left)"//; 
 1609:             s/<span.*?\/span>// if $category ne 'advtools'; 
 1610:         } 
 1611: 
 1612:         push @{$tools{$category}}, @html;
 1613:     }
 1614: 
 1615: =item clear_breadcrumb_tools()
 1616: 
 1617: Clears the breadcrumb toolbar container.
 1618: 
 1619: returns: nothing
 1620: 
 1621: =cut
 1622: 
 1623:     sub clear_breadcrumb_tools {
 1624:         undef(%tools);
 1625:     }
 1626: 
 1627: =item render_tools(\$breadcrumbs)
 1628: 
 1629: Creates html for breadcrumb tools (categories navigation and tools) and inserts 
 1630: \$breadcrumbs at the correct position.
 1631: 
 1632: input: \$breadcrumbs - a reference to the string containing prepared 
 1633: breadcrumbs.
 1634: 
 1635: returns: nothing
 1636: =cut
 1637: 
 1638: #TODO might split this in separate functions for each category
 1639:     sub render_tools {
 1640:         my ($breadcrumbs) = @_;
 1641:         return unless defined %tools;
 1642: 
 1643:         my $navigation = list_from_array($tools{navigation}, 
 1644:                    { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
 1645:         my $tools = list_from_array($tools{tools}, 
 1646:                    { listattr => { class=>"LC_breadcrumb_tools_tools" } });
 1647:         $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs], 
 1648:                    { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
 1649:     }
 1650: 
 1651: =item render_advtools(\$breadcrumbs)
 1652: 
 1653: Creates html for advanced tools (category advtools) and inserts \$breadcrumbs 
 1654: at the correct position.
 1655: 
 1656: input: \$breadcrumbs - a reference to the string containing prepared 
 1657: breadcrumbs (after render_tools call).
 1658: 
 1659: returns: nothing
 1660: =cut
 1661: 
 1662:     sub render_advtools {
 1663:         my ($breadcrumbs) = @_;
 1664:         return unless     (defined $tools{'advtools'}) 
 1665:                       and (scalar(@{$tools{'advtools'}}) > 0);
 1666: 
 1667:         $$breadcrumbs .= Apache::loncommon::head_subbox(
 1668:                             funclist_from_array($tools{'advtools'}) );
 1669:     }
 1670: 
 1671: } # End of scope for @Crumbs
 1672: 
 1673: ############################################################
 1674: ############################################################
 1675: 
 1676: # Nested table routines.
 1677: #
 1678: # Routines to display form items in a multi-row table with 2 columns.
 1679: # Uses nested tables to divide form elements into segments.
 1680: # For examples of use see loncom/interface/lonnotify.pm 
 1681: #
 1682: # Can be used in following order: ...
 1683: # &start_pick_box()
 1684: # row1
 1685: # row2
 1686: # row3   ... etc.
 1687: # &submit_row()
 1688: # &end_pick_box()
 1689: #
 1690: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
 1691: # &status_select_row and &email_default_row
 1692: #
 1693: # Can also be used in following order:
 1694: #
 1695: # &start_pick_box()
 1696: # &row_title()
 1697: # &row_closure()
 1698: # &row_title()
 1699: # &row_closure()  ... etc.
 1700: # &submit_row()
 1701: # &end_pick_box()
 1702: #
 1703: # In general a &submit_row() call should proceed the call to &end_pick_box(),
 1704: # as this routine adds a button for form submission.
 1705: # &submit_row() does not require a &row_closure after it.
 1706: #  
 1707: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
 1708: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
 1709: #
 1710: # &row_title() adds a title in the left column for each segment.
 1711: # &row_closure() closes a row with a 1-pixel wide black line.
 1712: #
 1713: # &role_select_row() provides a select box from which to choose 1 or more roles 
 1714: # &course_select_row provides ways of picking groups of courses
 1715: #    radio buttons: all, by category or by picking from a course picker pop-up
 1716: #      note: by category option is only displayed if a domain has implemented 
 1717: #                selection by year, semester, department, number etc.
 1718: #
 1719: # &status_select_row() provides a select box from which to choose 1 or more
 1720: #  access types (current access, prior access, and future access)  
 1721: #
 1722: # &email_default_row() provides text boxes for default e-mail suffixes for
 1723: #  different authentication types in a domain.
 1724: #
 1725: # &row_title() and &row_closure() are called internally by the &*_select_row
 1726: # routines, but can also be called directly to start and end rows which have 
 1727: # needs that are not accommodated by the *_select_row() routines.    
 1728: 
 1729: { # Start: row_count block for pick_box
 1730: my @row_count;
 1731: 
 1732: sub start_pick_box {
 1733:     my ($css_class) = @_;
 1734:     if (defined($css_class)) {
 1735: 	$css_class = 'class="'.$css_class.'"';
 1736:     } else {
 1737: 	$css_class= 'class="LC_pick_box"';
 1738:     }
 1739:     unshift(@row_count,0);
 1740:     my $output = <<"END";
 1741:  <table $css_class>
 1742: END
 1743:     return $output;
 1744: }
 1745: 
 1746: sub end_pick_box {
 1747:     shift(@row_count);
 1748:     my $output = <<"END";
 1749:        </table>
 1750: END
 1751:     return $output;
 1752: }
 1753: 
 1754: sub row_headline {
 1755:     my $output = <<"END";
 1756:            <tr><td colspan="2">
 1757: END
 1758:     return $output;
 1759: }
 1760: 
 1761: sub row_title {
 1762:     my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_;
 1763:     $row_count[0]++;
 1764:     my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 1765:     $css_title_class ||= 'LC_pick_box_title';
 1766:     $css_title_class = 'class="'.$css_title_class.'"';
 1767: 
 1768:     $css_value_class ||= 'LC_pick_box_value';
 1769: 
 1770:     if ($title ne '') {
 1771:         $title .= ':';
 1772:     }
 1773:     my $output = <<"ENDONE";
 1774:            <tr class="LC_pick_box_row" $css_value_furtherAttributes> 
 1775:             <td $css_title_class>
 1776: 	       $title
 1777:             </td>
 1778:             <td class="$css_value_class $css_class">
 1779: ENDONE
 1780:     return $output;
 1781: }
 1782: 
 1783: sub row_closure {
 1784:     my ($no_separator) =@_;
 1785:     my $output = <<"ENDTWO";
 1786:             </td>
 1787:            </tr>
 1788: ENDTWO
 1789:     if (!$no_separator) {
 1790:         $output .= <<"ENDTWO";
 1791:            <tr>
 1792:             <td colspan="2" class="LC_pick_box_separator">
 1793:             </td>
 1794:            </tr>
 1795: ENDTWO
 1796:     }
 1797:     return $output;
 1798: }
 1799: 
 1800: } # End: row_count block for pick_box
 1801: 
 1802: sub role_select_row {
 1803:     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
 1804:     my $crstype = 'Course';
 1805:     if ($cdom ne '' && $cnum ne '') {
 1806:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 1807:     }
 1808:     my $output;
 1809:     if (defined($title)) {
 1810:         $output = &row_title($title,$css_class);
 1811:     }
 1812:     $output .= qq|
 1813:                                   <select name="roles" multiple="multiple">\n|;
 1814:     foreach my $role (@$roles) {
 1815:         my $plrole;
 1816:         if ($role eq 'ow') {
 1817:             $plrole = &mt('Course Owner');
 1818:         } elsif ($role eq 'cr') {
 1819:             if ($show_separate_custom) {
 1820:                 if ($cdom ne '' && $cnum ne '') {
 1821:                     my %course_customroles = &course_custom_roles($cdom,$cnum);
 1822:                     foreach my $crrole (sort(keys(%course_customroles))) {
 1823:                         my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
 1824:                         $output .= '  <option value="'.$crrole.'">'.$plcrrole.
 1825:                                    '</option>';
 1826:                     }
 1827:                 }
 1828:             } else {
 1829:                 $plrole = &mt('Custom Role');
 1830:             }
 1831:         } else {
 1832:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 1833:         }
 1834:         if (($role ne 'cr') || (!$show_separate_custom)) {
 1835:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1836:         }
 1837:     }
 1838:     $output .= qq|                </select>\n|;
 1839:     if (defined($title)) {
 1840:         $output .= &row_closure();
 1841:     }
 1842:     return $output;
 1843: }
 1844: 
 1845: sub course_select_row {
 1846:     my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 1847: 	$css_class,$crstype,$standardnames) = @_;
 1848:     my $output = &row_title($title,$css_class);
 1849:     $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames);
 1850:     $output .= &row_closure();
 1851:     return $output;
 1852: }
 1853: 
 1854: sub course_selection {
 1855:     my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames) = @_;
 1856:     my $output = qq|
 1857: <script type="text/javascript">
 1858: // <![CDATA[
 1859:     function coursePick (formname) {
 1860:         for  (var i=0; i<formname.coursepick.length; i++) {
 1861:             if (formname.coursepick[i].value == 'category') {
 1862:                 courseSet('');
 1863:             }
 1864:             if (!formname.coursepick[i].checked) {
 1865:                 if (formname.coursepick[i].value == 'specific') {
 1866:                     formname.coursetotal.value = 0;
 1867:                     formname.courselist = '';
 1868:                 }
 1869:             }
 1870:         }
 1871:     }
 1872:     function setPick (formname) {
 1873:         for  (var i=0; i<formname.coursepick.length; i++) {
 1874:             if (formname.coursepick[i].value == 'category') {
 1875:                 formname.coursepick[i].checked = true;
 1876:             }
 1877:             formname.coursetotal.value = 0;
 1878:             formname.courselist = '';
 1879:         }
 1880:     }
 1881: // ]]>
 1882: </script>
 1883:     |;
 1884: 
 1885:     my ($allcrs,$pickspec);
 1886:     if ($crstype eq 'Community') {
 1887:         $allcrs = &mt('All communities');
 1888:         $pickspec = &mt('Pick specific communities:');
 1889:     } else {
 1890:         $allcrs = &mt('All courses');
 1891:         $pickspec = &mt('Pick specific course(s):');
 1892:     }
 1893: 
 1894:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
 1895:                      ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).'</b>';
 1896:         $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.$allcrs.'<br />';
 1897:     if ($totcodes > 0) {
 1898:         my $numtitles = @$codetitles;
 1899:         if ($numtitles > 0) {
 1900:             $output .= '<input type="radio" name="coursepick" value="category" onclick="coursePick(this.form);alert('."'".&mt('Choose categories, from left to right')."'".')" />'.&mt('Pick courses by category:').' <br />';
 1901:             $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
 1902:                '<select name="'.$standardnames->[0].
 1903:                '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
 1904:                ' <option value="-1" />Select'."\n";
 1905:             my @items = ();
 1906:             my @longitems = ();
 1907:             if ($$idlist{$$codetitles[0]} =~ /","/) {
 1908:                 @items = split(/","/,$$idlist{$$codetitles[0]});
 1909:             } else {
 1910:                 $items[0] = $$idlist{$$codetitles[0]};
 1911:             }
 1912:             if (defined($$idlist_titles{$$codetitles[0]})) {
 1913:                 if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
 1914:                     @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
 1915:                 } else {
 1916:                     $longitems[0] = $$idlist_titles{$$codetitles[0]};
 1917:                 }
 1918:                 for (my $i=0; $i<@longitems; $i++) {
 1919:                     if ($longitems[$i] eq '') {
 1920:                         $longitems[$i] = $items[$i];
 1921:                     }
 1922:                 }
 1923:             } else {
 1924:                 @longitems = @items;
 1925:             }
 1926:             for (my $i=0; $i<@items; $i++) {
 1927:                 $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
 1928:             }
 1929:             $output .= '</select></td>';
 1930:             for (my $i=1; $i<$numtitles; $i++) {
 1931:                 $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
 1932:                           '<select name="'.$standardnames->[$i].
 1933:                           '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
 1934:                           '<option value="-1">&lt;-Pick '.$$codetitles[$i-1].'</option>'."\n".
 1935:                           '</select>'."\n".
 1936:                           '</td>';
 1937:             }
 1938:             $output .= '</tr></table><br />';
 1939:         }
 1940:     }
 1941:     $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1','$crstype'".')" />'.$pickspec.' '.$courseform.'&nbsp;&nbsp;<input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
 1942:     return $output;
 1943: }
 1944: 
 1945: sub status_select_row {
 1946:     my ($types,$title,$css_class) = @_;
 1947:     my $output; 
 1948:     if (defined($title)) {
 1949:         $output = &row_title($title,$css_class,'LC_pick_box_select');
 1950:     }
 1951:     $output .= qq|
 1952:                                     <select name="types" multiple="multiple">\n|;
 1953:     foreach my $status_type (sort(keys(%{$types}))) {
 1954:         $output .= '  <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
 1955:     }
 1956:     $output .= qq|                   </select>\n|; 
 1957:     if (defined($title)) {
 1958:         $output .= &row_closure();
 1959:     }
 1960:     return $output;
 1961: }
 1962: 
 1963: sub email_default_row {
 1964:     my ($authtypes,$title,$descrip,$css_class) = @_;
 1965:     my $output = &row_title($title,$css_class);
 1966:     $output .= $descrip.
 1967: 	&Apache::loncommon::start_data_table().
 1968: 	&Apache::loncommon::start_data_table_header_row().
 1969: 	'<th>'.&mt('Authentication Method').'</th>'.
 1970: 	'<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
 1971: 	&Apache::loncommon::end_data_table_header_row();
 1972:     my $rownum = 0;
 1973:     foreach my $auth (sort(keys(%{$authtypes}))) {
 1974:         my ($userentry,$size);
 1975:         if ($auth =~ /^krb/) {
 1976:             $userentry = '';
 1977:             $size = 25;
 1978:         } else {
 1979:             $userentry = 'username@';
 1980:             $size = 15;
 1981:         }
 1982:         $output .= &Apache::loncommon::start_data_table_row().
 1983: 	    '<td>  '.$$authtypes{$auth}.'</td>'.
 1984: 	    '<td align="right">'.$userentry.
 1985: 	    '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
 1986: 	    &Apache::loncommon::end_data_table_row();
 1987:     }
 1988:     $output .= &Apache::loncommon::end_data_table();
 1989:     $output .= &row_closure();
 1990:     return $output;
 1991: }
 1992: 
 1993: 
 1994: sub submit_row {
 1995:     my ($title,$cmd,$submit_text,$css_class) = @_;
 1996:     my $output = &row_title($title,$css_class,'LC_pick_box_submit');
 1997:     $output .= qq|
 1998:              <br />
 1999:              <input type="hidden" name="command" value="$cmd" />
 2000:              <input type="submit" value="$submit_text"/> &nbsp;
 2001:              <br /><br />
 2002:             \n|;
 2003:     return $output;
 2004: }
 2005: 
 2006: sub course_custom_roles {
 2007:     my ($cdom,$cnum) = @_;
 2008:     my %returnhash=();
 2009:     my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 2010:     foreach my $person (sort(keys(%coursepersonnel))) {
 2011:         my ($role) = ($person =~ /^([^:]+):/);
 2012:         my ($end,$start) = split(/:/,$coursepersonnel{$person});
 2013:         if ($end == -1 && $start == -1) {
 2014:             next;
 2015:         }
 2016:         if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
 2017:             $returnhash{$role} ++;
 2018:         }
 2019:     }
 2020:     return %returnhash;
 2021: }
 2022: 
 2023: 
 2024: sub resource_info_box {
 2025:    my ($symb,$onlyfolderflag)=@_;
 2026:    my $return='';
 2027:    if ($symb) {
 2028:        $return=&Apache::loncommon::start_data_table();
 2029:        my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
 2030:        my $folder=&Apache::lonnet::gettitle($map);
 2031:        $return.=&Apache::loncommon::start_data_table_row().
 2032:                     '<th>'.&mt('Folder:').'</th><td>'.$folder.'</td>'.
 2033:                     &Apache::loncommon::end_data_table_row();
 2034:        unless ($onlyfolderflag) {
 2035:           $return.=&Apache::loncommon::start_data_table_row().
 2036:                     '<th>'.&mt('Resource:').'</th><td>'.&Apache::lonnet::gettitle($symb).'</td>'.
 2037:                     &Apache::loncommon::end_data_table_row();
 2038:        }
 2039:        $return.=&Apache::loncommon::end_data_table();
 2040:     } else {
 2041:        $return='<p><span class="LC_error">'.&mt('No context provided.').'</span></p>';
 2042:     }
 2043:     return $return;
 2044: 
 2045: }
 2046: 
 2047: ##############################################
 2048: ##############################################
 2049: 
 2050: # topic_bar
 2051: #
 2052: # Generates a div containing an (optional) number with a white background followed by a 
 2053: # title with a background color defined in the corresponding CSS: LC_topic_bar
 2054: # Inputs:
 2055: # 1. number to display.
 2056: #    If input for number is empty only the title will be displayed. 
 2057: # 2. title text to display.
 2058: # Outputs - a scalar containing html mark-up for the div.
 2059: 
 2060: sub topic_bar {
 2061:     my ($num,$title) = @_;
 2062:     my $number = '';
 2063:     if ($num ne '') {
 2064:         $number = '<span>'.$num.'</span>';
 2065:     }
 2066:     return '<div class="LC_topic_bar">'.$number.$title.'</div>';
 2067: }
 2068: 
 2069: ##############################################
 2070: ##############################################
 2071: # echo_form_input
 2072: #
 2073: # Generates html markup to add form elements from the referrer page
 2074: # as hidden form elements (values encoded) in the new page.
 2075: #
 2076: # Intended to support two types of use 
 2077: # (a) to allow backing up to earlier pages in a multi-page 
 2078: # form submission process using a breadcrumb trail.
 2079: #
 2080: # (b) to allow the current page to be reloaded with form elements
 2081: # set on previous page to remain unchanged.  An example would
 2082: # be where the a page containing a dynamically-built table of data is 
 2083: # is to be redisplayed, with only the sort order of the data changed. 
 2084: #  
 2085: # Inputs:
 2086: # 1. Reference to array of form elements in the submitted form on 
 2087: # the referrer page which are to be excluded from the echoed elements.
 2088: #
 2089: # 2. Reference to array of regular expressions, which if matched in the  
 2090: # name of the form element n the referrer page will be omitted from echo. 
 2091: #
 2092: # Outputs: A scalar containing the html markup for the echoed form
 2093: # elements (all as hidden elements, with values encoded). 
 2094: 
 2095: 
 2096: sub echo_form_input {
 2097:     my ($excluded,$regexps) = @_;
 2098:     my $output = '';
 2099:     foreach my $key (keys(%env)) {
 2100:         if ($key =~ /^form\.(.+)$/) {
 2101:             my $name = $1;
 2102:             my $match = 0;
 2103:             if ((!@{$excluded}) || (!grep/^$name$/,@{$excluded})) {
 2104:                 if (defined($regexps)) {
 2105:                     if (@{$regexps} > 0) {
 2106:                         foreach my $regexp (@{$regexps}) {
 2107:                             if ($name =~ /\Q$regexp\E/) {
 2108:                                 $match = 1;
 2109:                                 last;
 2110:                             }
 2111:                         }
 2112:                     }
 2113:                 }
 2114:                 if (!$match) {
 2115:                     if (ref($env{$key})) {
 2116:                         foreach my $value (@{$env{$key}}) {
 2117:                             $value = &HTML::Entities::encode($value,'<>&"');
 2118:                             $output .= '<input type="hidden" name="'.$name.
 2119:                                              '" value="'.$value.'" />'."\n";
 2120:                         }
 2121:                     } else {
 2122:                         my $value = &HTML::Entities::encode($env{$key},'<>&"');
 2123:                         $output .= '<input type="hidden" name="'.$name.
 2124:                                              '" value="'.$value.'" />'."\n";
 2125:                     }
 2126:                 }
 2127:             }
 2128:         }
 2129:     }
 2130:     return $output;
 2131: }
 2132: 
 2133: ##############################################
 2134: ##############################################
 2135: # set_form_elements
 2136: #
 2137: # Generates javascript to set form elements to values based on
 2138: # corresponding values for the same form elements when the page was
 2139: # previously submitted.
 2140: #     
 2141: # Last submission values are read from hidden form elements in referring 
 2142: # page which have the same name, i.e., generated by &echo_form_input(). 
 2143: #
 2144: # Intended to be called by onload event.
 2145: #
 2146: # Inputs:
 2147: # (a) Reference to hash of echoed form elements to be set.
 2148: #
 2149: # In the hash, keys are the form element names, and the values are the
 2150: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
 2151: # hidden).
 2152: #
 2153: # (b) Optional reference to hash of stored elements to be set.
 2154: #
 2155: # If the page being displayed is a page which permits modification of
 2156: # previously stored data, e.g., the first page in a multi-page submission,
 2157: # then if stored is supplied, form elements will be set to the last stored
 2158: # values.  If user supplied values are also available for the same elements
 2159: # these will replace the stored values. 
 2160: #        
 2161: # Output:
 2162: #  
 2163: # javascript function - set_form_elements() which sets form elements,
 2164: # expects an argument: formname - the name of the form according to 
 2165: # the DOM, e.g., document.compose
 2166: 
 2167: sub set_form_elements {
 2168:     my ($elements,$stored) = @_;
 2169:     my %values;
 2170:     my $output .= 'function setFormElements(courseForm) {
 2171: ';
 2172:     if (defined($stored)) {
 2173:         foreach my $name (keys(%{$stored})) {
 2174:             if (exists($$elements{$name})) {
 2175:                 if (ref($$stored{$name}) eq 'ARRAY') {
 2176:                     $values{$name} = $$stored{$name};
 2177:                 } else {
 2178:                     @{$values{$name}} = ($$stored{$name});
 2179:                 }
 2180:             }
 2181:         }
 2182:     }
 2183: 
 2184:     foreach my $key (keys(%env)) {
 2185:         if ($key =~ /^form\.(.+)$/) {
 2186:             my $name = $1;
 2187:             if (exists($$elements{$name})) {
 2188:                 @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
 2189:             }
 2190:         }
 2191:     }
 2192: 
 2193:     foreach my $name (keys(%values)) {
 2194:         for (my $i=0; $i<@{$values{$name}}; $i++) {
 2195:             $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
 2196:             $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
 2197:             $values{$name}[$i] =~ s/"/\\"/g;
 2198:         }
 2199:         if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) {
 2200:             my $numvalues = @{$values{$name}};
 2201:             if ($numvalues > 1) {
 2202:                 my $valuestring = join('","',@{$values{$name}});
 2203:                 $output .= qq|
 2204:   var textvalues = new Array ("$valuestring");
 2205:   var total = courseForm.elements['$name'].length;
 2206:   if (total > $numvalues) {
 2207:       total = $numvalues;
 2208:   }    
 2209:   for (var i=0; i<total; i++) {
 2210:       courseForm.elements['$name']\[i].value = textvalues[i];
 2211:   }
 2212: |;
 2213:             } else {
 2214:                 $output .= qq|
 2215:   courseForm.elements['$name'].value = "$values{$name}[0]";
 2216: |;
 2217:             }
 2218:         } else {
 2219:             $output .=  qq|
 2220:   var elementLength = courseForm.elements['$name'].length;
 2221:   if (elementLength==undefined) {
 2222: |;
 2223:             foreach my $value (@{$values{$name}}) {
 2224:                 if ($$elements{$name} eq 'selectbox') {
 2225:                     $output .=  qq|
 2226:       if (courseForm.elements['$name'].options[0].value == "$value") {
 2227:           courseForm.elements['$name'].options[0].selected = true;
 2228:       }|;
 2229:                 } elsif (($$elements{$name} eq 'radio') ||
 2230:                          ($$elements{$name} eq 'checkbox')) {
 2231:                     $output .= qq|
 2232:       if (courseForm.elements['$name'].value == "$value") {
 2233:           courseForm.elements['$name'].checked = true;
 2234:       } else {
 2235:           courseForm.elements['$name'].checked = false;
 2236:       }|;
 2237:                 }
 2238:             }
 2239:             $output .= qq|
 2240:   }
 2241:   else {
 2242:       for (var i=0; i<courseForm.elements['$name'].length; i++) {
 2243: |;
 2244:             if ($$elements{$name} eq 'selectbox') {
 2245:                 $output .=  qq|
 2246:           courseForm.elements['$name'].options[i].selected = false;|;
 2247:             } elsif (($$elements{$name} eq 'radio') || 
 2248:                      ($$elements{$name} eq 'checkbox')) {
 2249:                 $output .= qq|
 2250:           courseForm.elements['$name']\[i].checked = false;|; 
 2251:             }
 2252:             $output .= qq|
 2253:       }
 2254:       for (var j=0; j<courseForm.elements['$name'].length; j++) {
 2255: |;
 2256:             foreach my $value (@{$values{$name}}) {
 2257:                 if ($$elements{$name} eq 'selectbox') {
 2258:                     $output .=  qq|
 2259:           if (courseForm.elements['$name'].options[j].value == "$value") {
 2260:               courseForm.elements['$name'].options[j].selected = true;
 2261:           }|;
 2262:                 } elsif (($$elements{$name} eq 'radio') ||
 2263:                          ($$elements{$name} eq 'checkbox')) { 
 2264:                       $output .= qq|
 2265:           if (courseForm.elements['$name']\[j].value == "$value") {
 2266:               courseForm.elements['$name']\[j].checked = true;
 2267:           }|;
 2268:                 }
 2269:             }
 2270:             $output .= qq|
 2271:       }
 2272:   }
 2273: |;
 2274:         }
 2275:     }
 2276:     $output .= "
 2277:     return;
 2278: }\n";
 2279:     return $output;
 2280: }
 2281: 
 2282: ##############################################
 2283: ##############################################
 2284: 
 2285: # javascript_valid_email
 2286: #
 2287: # Generates javascript to validate an e-mail address.
 2288: # Returns a javascript function which accetps a form field as argumnent, and
 2289: # returns false if field.value does not satisfy two regular expression matches
 2290: # for a valid e-mail address.  Backwards compatible with old browsers without
 2291: # support for javascript RegExp (just checks for @ in field.value in this case). 
 2292: 
 2293: sub javascript_valid_email {
 2294:     my $scripttag .= <<'END';
 2295: function validmail(field) {
 2296:     var str = field.value;
 2297:     if (window.RegExp) {
 2298:         var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
 2299:         var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
 2300:         var reg1 = new RegExp(reg1str);
 2301:         var reg2 = new RegExp(reg2str);
 2302:         if (!reg1.test(str) && reg2.test(str)) {
 2303:             return true;
 2304:         }
 2305:         return false;
 2306:     }
 2307:     else
 2308:     {
 2309:         if(str.indexOf("@") >= 0) {
 2310:             return true;
 2311:         }
 2312:         return false;
 2313:     }
 2314: }
 2315: END
 2316:     return $scripttag;
 2317: }
 2318: 
 2319: 
 2320: # USAGE: htmltag(element, content, {attribute => value,...});
 2321: #
 2322: # EXAMPLES: 
 2323: #  - htmltag('a', 'this is an anchor', {href  => 'www.example.com', 
 2324: #                                       title => 'this is a title'})
 2325: #
 2326: #  - You might want to set up needed tags like: 
 2327: #
 2328: #     my $h3  = sub { return htmltag( "h3",  @_ ) };
 2329: #
 2330: #    ... and use them: $h3->("This is a headline")
 2331: #
 2332: #  - To set up a couple of tags, see sub inittags
 2333: #
 2334: # NOTES:
 2335: # - Empty elements, such as <br/> are correctly terminated, 
 2336: #   i.e. htmltag('br') returns <br/> 
 2337: # - Empty attributes (title="") are filtered out.
 2338: # - The function will not check for deprecated attributes.
 2339: #
 2340: # OUTPUT: content enclosed in xhtml conform tags
 2341: sub htmltag{
 2342:     return
 2343:         qq|<$_[0]|
 2344:         . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } )
 2345:         . ($_[1] ? qq|>$_[1]</$_[0]>| : qq|/>|). "\n";
 2346: };
 2347: 
 2348: 
 2349: # USAGE: inittags(@tags);
 2350: #
 2351: # EXAMPLES:
 2352: #  - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) )
 2353: #    $h1->("This is a headline") #Returns: <h1>This is a headline</h1>
 2354: #
 2355: # NOTES: See sub htmltag for further information.
 2356: #
 2357: # OUTPUT: List of subroutines. 
 2358: sub inittags {
 2359:     my @tags = @_;
 2360:     return map { my $tag = $_;
 2361:                  sub { return htmltag( $tag, @_ ) }
 2362:                } @tags;
 2363: }
 2364: 
 2365: 
 2366: # USAGE: scripttag(scriptcode, [start|end|both]);
 2367: #
 2368: # EXAMPLES: 
 2369: #  - scripttag("alert('Hello World!')", 'both') 
 2370: #    returns:
 2371: #    <script type="text/javascript">
 2372: #    // BEGIN LON-CAPA Internal
 2373: #    alert(Hello World!')
 2374: #    // END LON-CAPA Internal
 2375: #    </script>
 2376: #
 2377: # NOTES:
 2378: # - works currently only for javascripts
 2379: #
 2380: # OUTPUT: 
 2381: # Scriptcode properly enclosed in <script> and CDATA tags (and LC
 2382: # Internal markers if 2nd argument is given)
 2383: sub scripttag {
 2384:     my ( $content, $marker ) = @_;
 2385:     return unless defined $content;
 2386: 
 2387:     my $begin = "\n// BEGIN LON-CAPA Internal\n";
 2388:     my $end   = "\n// END LON-CAPA Internal\n";
 2389: 
 2390:     if ($marker) {
 2391:         $content  = $begin . $content if $marker eq 'start' or $marker eq 'both';
 2392:         $content .= $end              if $marker eq 'end'   or $marker eq 'both';
 2393:     }
 2394: 
 2395:     $content = "\n// <![CDATA[\n$content\n// ]]>\n";
 2396: 
 2397:     return htmltag('script', $content, {type => 'text/javascript'});
 2398: };
 2399: 
 2400: 
 2401: =item list_from_array( \@array, { listattr =>{}, itemattr =>{} } )
 2402: 
 2403: Constructs a XHTML list from \@array.
 2404: 
 2405: input: 
 2406: 
 2407: =over
 2408: 
 2409: =item \@array 
 2410: 
 2411: A reference to the array containing text that will be wrapped in <li></li> tags.
 2412: 
 2413: =item { listattr => {}, itemattr =>{} } 
 2414: 
 2415: Attributes for <ul> and <li> passed in as hash references. 
 2416: See htmltag() for more details.
 2417: 
 2418: =back
 2419:  
 2420: returns: XHTML list as String. 
 2421: 
 2422: =cut   
 2423: 
 2424: # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
 2425: sub list_from_array {
 2426:     my ($items, $args) = @_;
 2427:     return unless scalar @$items;
 2428:     my ($ul, $li) = inittags( qw(ul li) );
 2429:     my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
 2430:     return $ul->( $listitems, $args->{listattr} );
 2431: }
 2432: 
 2433: 
 2434: ##############################################
 2435: ##############################################
 2436: 
 2437: # generate_menu
 2438: #
 2439: # Generates html markup for a menu. 
 2440: #
 2441: # Inputs:
 2442: # An array of following structure:
 2443: #   ({	categorytitle => 'Categorytitle',
 2444: #	items => [
 2445: #		    {	
 2446: #           linktext    =>	'Text to be displayed',
 2447: #			url	        =>	'URL the link is pointing to, i.e. /adm/site?action=dosomething',
 2448: #			permission  =>	'Contains permissions as returned from lonnet::allowed(),
 2449: #					         must evaluate to true in order to activate the link',
 2450: #			icon        =>  'icon filename',
 2451: #			alttext	    =>	'alt text for the icon',
 2452: #			help	    =>	'Name of the corresponding helpfile',
 2453: #			linktitle   =>	'Description of the link (used for title tag)'
 2454: #		    },
 2455: #		    ...
 2456: #		]
 2457: #   }, 
 2458: #   ...
 2459: #   )
 2460: #
 2461: # Outputs: A scalar containing the html markup for the menu.
 2462: 
 2463: sub generate_menu {
 2464:     my @menu = @_;
 2465:     # subs for specific html elements
 2466:     my ($h3, $div, $ul, $li, $a, $img) = inittags( qw(h3 div ul li a img) ); 
 2467:     
 2468:     my @categories; # each element represents the entire markup for a category
 2469:    
 2470:     foreach my $category (@menu) {
 2471:         my @links;  # contains the links for the current $category
 2472:         foreach my $link (@{$$category{items}}) {
 2473:             next unless $$link{permission};
 2474:             
 2475:             # create the markup for the current $link and push it into @links.
 2476:             # each entry consists of an image and a text optionally followed 
 2477:             # by a help link.
 2478:             push(@links,$li->(
 2479:                         $a->(
 2480:                             $img->("", {
 2481:                                 class => "LC_noBorder LC_middle",
 2482:                                 src   => "/res/adm/pages/$$link{icon}",
 2483:                                 alt   => mt(defined($$link{alttext}) ?
 2484:                                 $$link{alttext} : $$link{linktext})
 2485:                             }), {
 2486:                             href  => $$link{url},
 2487:                             title => mt($$link{linktitle})
 2488:                             }).
 2489:                         $a->(mt($$link{linktext}), {
 2490:                             href  => $$link{url},
 2491:                             title => mt($$link{linktitle}),
 2492:                             class => "LC_menubuttons_link"
 2493:                             }).
 2494:                          (defined($$link{help}) ? 
 2495:                          Apache::loncommon::help_open_topic($$link{help}) : ''),
 2496:                          {class => "LC_menubuttons_inline_text"}));
 2497:         }
 2498: 
 2499:         # wrap categorytitle in <h3>, concatenate with 
 2500:         # joined and in <ul> tags wrapped @links
 2501:         # and wrap everything in an enclosing <div> and push it into
 2502:         # @categories
 2503:         # such that each element looks like:
 2504:         # <div><h3>title</h3><ul><li>...</li>...</ul></div>
 2505:         # the category won't be added if there aren't any links
 2506:         push(@categories, 
 2507:             $div->($h3->(mt($$category{categorytitle}), {class=>"LC_hcell"}).
 2508:             $ul->(join('' ,@links),  {class =>"LC_ListStyleNormal" }),
 2509:             {class=>"LC_Box LC_400Box"})) if scalar(@links);
 2510:     }
 2511: 
 2512:     # wrap the joined @categories in another <div> (column layout)
 2513:     return $div->(join('', @categories), {class => "LC_columnSection"});
 2514: }
 2515: 
 2516: ##############################################
 2517: ##############################################
 2518: 
 2519: =pod
 2520: 
 2521: =item &start_funclist
 2522: 
 2523: Start list of available functions
 2524: 
 2525: Typically used to offer a simple list of available functions
 2526: at top or bottom of page.
 2527: All available functions/actions for the current page
 2528: should be included in this list.
 2529: 
 2530: If the optional headline text is not provided, a default text will be used.
 2531: 
 2532: 
 2533: Related routines:
 2534: =over 4
 2535: add_item_funclist
 2536: end_funclist
 2537: =back
 2538: 
 2539: 
 2540: Inputs: (optional) headline text
 2541: 
 2542: Returns: HTML code with function list start
 2543: 
 2544: =cut
 2545: 
 2546: ##############################################
 2547: ##############################################
 2548: 
 2549: sub start_funclist {
 2550:     my($legendtext)=@_;
 2551:     $legendtext=&mt('Functions') if !$legendtext;
 2552:     return '<ul class="LC_funclist"><li style="font-weight:bold; margin-left:0.8em;">'.$legendtext.'</li>'."\n";
 2553: }
 2554: 
 2555: 
 2556: ##############################################
 2557: ##############################################
 2558: 
 2559: =pod
 2560: 
 2561: =item &add_item_funclist
 2562: 
 2563: Adds an item to the list of available functions
 2564: 
 2565: Related routines:
 2566: =over 4
 2567: start_funclist
 2568: end_funclist
 2569: =back
 2570: 
 2571: Inputs: content item with text and link to function
 2572: 
 2573: Returns: HTML code with list item for funclist
 2574: 
 2575: =cut
 2576: 
 2577: ##############################################
 2578: ##############################################
 2579: 
 2580: sub add_item_funclist {
 2581:     my($content) = @_;
 2582:     return '<li>'.$content.'</li>'."\n";
 2583: }
 2584: 
 2585: =pod
 2586: 
 2587: =item &end_funclist
 2588: 
 2589: End list of available functions
 2590: 
 2591: Related routines:
 2592: =over 4
 2593: start_funclist
 2594: add_item_funclist
 2595: =back
 2596: 
 2597: Inputs: ./.
 2598: 
 2599: Returns: HTML code with function list end
 2600: =cut
 2601: 
 2602: sub end_funclist {
 2603:     return "</ul>\n";
 2604: }
 2605: 
 2606: =pod
 2607: 
 2608: =item funclist_from_array( \@array, {legend => 'text for legend'} )
 2609: 
 2610: Constructs a XHTML list from \@array with the first item being visually
 2611: highlighted and set to the value of legend or 'Functions' if legend is
 2612: empty. 
 2613: 
 2614: =over
 2615: 
 2616: =item \@array
 2617: 
 2618: A reference to the array containing text that will be wrapped in <li></li> tags.
 2619: 
 2620: =item { legend => 'text' }
 2621: 
 2622: A string that's used as visually highlighted first item. 'Functions' is used if
 2623: it's value evaluates to false.
 2624: 
 2625: =back
 2626:  
 2627: returns: XHTML list as string. 
 2628: 
 2629: =back
 2630: 
 2631: =cut  
 2632: 
 2633: sub funclist_from_array {
 2634:     my ($items, $args) = @_;
 2635:     $args->{legend} ||= mt('Functions');
 2636:     return list_from_array( [$args->{legend}, @$items], 
 2637:                { listattr => {class => 'LC_funclist'} });
 2638: }   
 2639: 
 2640: 1;
 2641: 
 2642: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>