File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.178: download - view: text, annotated - select for diffs
Thu Aug 21 10:48:37 2008 UTC (15 years, 9 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Localization:
Added missing &mt() call to "Edit Math" button text

    1: # The LearningOnline Network with CAPA
    2: # a pile of common html routines
    3: #
    4: # $Id: lonhtmlcommon.pm,v 1.178 2008/08/21 10:48:37 bisitz 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: ##############################################
   67: ##############################################
   68: 
   69: =pod
   70: 
   71: =item dragmath_button
   72: 
   73: Creates a button that launches a dragmath popup-window, in which an 
   74: expression can be edited and pasted as LaTeX into a specified textarea. 
   75: 
   76:   textarea - Name of the textarea to edit.
   77:   helpicon - If true, show a help icon to the right of the button.
   78: 
   79: =cut
   80: 
   81: sub dragmath_button {
   82:     my ($textarea,$helpicon) = @_;
   83:     my $help_text; 
   84:     if ($helpicon) {
   85:         $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor');
   86:     }
   87:     my $buttontext=&mt('Edit Math');
   88:     return <<ENDDRAGMATH;
   89:                 <input type="button" value="$buttontext", onclick="javascript:mathedit('$textarea',document)" />$help_text
   90: ENDDRAGMATH
   91: }
   92: 
   93: ##############################################
   94: 
   95: =pod
   96: 
   97: =item dragmath_js
   98: 
   99: Javascript used to open pop-up window containing dragmath applet which 
  100: can be used to paste LaTeX into a textarea.
  101:  
  102: =cut
  103: 
  104: sub dragmath_js {
  105:     return <<ENDDRAGMATHJS;
  106:                 <script type="text/javascript">
  107:                   function mathedit(textarea, doc) {
  108:                      targetEntry = textarea;
  109:                      targetDoc   = doc;
  110:                      newwin  = window.open("/adm/dragmath/applet/EditMathPopup.html","","width=565,height=500,resizable");
  111:                   }
  112:                 </script>
  113: 
  114: ENDDRAGMATHJS
  115: }
  116: 
  117: ##############################################
  118: ##############################################
  119: 
  120: =pod
  121: 
  122: =item authorbombs
  123: 
  124: =cut
  125: 
  126: ##############################################
  127: ##############################################
  128: 
  129: sub authorbombs {
  130:     my $url=shift;
  131:     $url=&Apache::lonnet::declutter($url);
  132:     my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
  133:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
  134:     foreach (keys %bombs) {
  135: 	if ($_=~/^$udom\/$uname\//) {
  136: 	    return '<a href="/adm/bombs/'.$url.
  137: 		'"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" border="0" /></a>'.
  138: 		&Apache::loncommon::help_open_topic('About_Bombs');
  139: 	}
  140:     }
  141:     return '';
  142: }
  143: 
  144: ##############################################
  145: ##############################################
  146: 
  147: sub recent_filename {
  148:     my $area=shift;
  149:     return 'nohist_recent_'.&escape($area);
  150: }
  151: 
  152: sub store_recent {
  153:     my ($area,$name,$value,$freeze)=@_;
  154:     my $file=&recent_filename($area);
  155:     my %recent=&Apache::lonnet::dump($file);
  156:     if (scalar(keys(%recent))>20) {
  157: # remove oldest value
  158: 	my $oldest=time();
  159: 	my $delkey='';
  160: 	foreach my $item (keys(%recent)) {
  161: 	    my $thistime=(split(/\&/,$recent{$item}))[0];
  162: 	    if (($thistime ne "always_include") && ($thistime<$oldest)) {
  163: 		$oldest=$thistime;
  164: 		$delkey=$item;
  165: 	    }
  166: 	}
  167: 	&Apache::lonnet::del($file,[$delkey]);
  168:     }
  169: # store new value
  170:     my $timestamp;
  171:     if ($freeze) {
  172:         $timestamp = "always_include";
  173:     } else {
  174:         $timestamp = time();
  175:     }   
  176:     &Apache::lonnet::put($file,{ $name => 
  177: 				 $timestamp.'&'.&escape($value) });
  178: }
  179: 
  180: sub remove_recent {
  181:     my ($area,$names)=@_;
  182:     my $file=&recent_filename($area);
  183:     return &Apache::lonnet::del($file,$names);
  184: }
  185: 
  186: sub select_recent {
  187:     my ($area,$fieldname,$event)=@_;
  188:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  189:     my $return="\n<select name='$fieldname'".
  190: 	($event?" onchange='$event'":'').
  191: 	">\n<option value=''>--- ".&mt('Recent')." ---</option>";
  192:     foreach my $value (sort(keys(%recent))) {
  193: 	unless ($value =~/^error\:/) {
  194: 	    my $escaped = &Apache::loncommon::escape_url($value);
  195: 	    &Apache::loncommon::inhibit_menu_check(\$escaped);
  196: 	    $return.="\n<option value='$escaped'>".
  197: 		&unescape((split(/\&/,$recent{$value}))[1]).
  198: 		'</option>';
  199: 	}
  200:     }
  201:     $return.="\n</select>\n";
  202:     return $return;
  203: }
  204: 
  205: sub get_recent {
  206:     my ($area, $n) = @_;
  207:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  208: 
  209: # Create hash with key as time and recent as value
  210: # Begin filling return_hash with any 'always_include' option
  211:     my %time_hash = ();
  212:     my %return_hash = ();
  213:     foreach my $item (keys %recent) {
  214:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  215:         if ($thistime eq 'always_include') {
  216:             $return_hash{$item} = &unescape($thisvalue);
  217:             $n--;
  218:         } else {
  219:             $time_hash{$thistime} = $item;
  220:         }
  221:     }
  222: 
  223: # Sort by decreasing time and return key value pairs
  224:     my $idx = 1;
  225:     foreach my $item (reverse(sort(keys(%time_hash)))) {
  226:        $return_hash{$time_hash{$item}} =
  227:                   &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
  228:        if ($n && ($idx++ >= $n)) {last;}
  229:     }
  230: 
  231:     return %return_hash;
  232: }
  233: 
  234: sub get_recent_frozen {
  235:     my ($area) = @_;
  236:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  237: 
  238: # Create hash with all 'frozen' items
  239:     my %return_hash = ();
  240:     foreach my $item (keys(%recent)) {
  241:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  242:         if ($thistime eq 'always_include') {
  243:             $return_hash{$item} = &unescape($thisvalue);
  244:         }
  245:     }
  246:     return %return_hash;
  247: }
  248: 
  249: 
  250: 
  251: =pod
  252: 
  253: =item textbox
  254: 
  255: =cut
  256: 
  257: ##############################################
  258: ##############################################
  259: sub textbox {
  260:     my ($name,$value,$size,$special) = @_;
  261:     $size = 40 if (! defined($size));
  262:     $value = &HTML::Entities::encode($value,'<>&"');
  263:     my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
  264:         'value="'.$value.'" '.$special.' />';
  265:     return $Str;
  266: }
  267: 
  268: ##############################################
  269: ##############################################
  270: 
  271: =pod
  272: 
  273: =item checkbox
  274: 
  275: =cut
  276: 
  277: ##############################################
  278: ##############################################
  279: sub checkbox {
  280:     my ($name,$checked,$value) = @_;
  281:     my $Str = '<input type="checkbox" name="'.$name.'" ';
  282:     if (defined($value)) {
  283:         $Str .= 'value="'.$value.'"';
  284:     } 
  285:     if ($checked) {
  286:         $Str .= ' checked="1"';
  287:     }
  288:     $Str .= ' />';
  289:     return $Str;
  290: }
  291: 
  292: 
  293: =pod
  294: 
  295: =item radiobutton
  296: 
  297: =cut
  298: 
  299: ##############################################
  300: ##############################################
  301: sub radio {
  302:     my ($name,$checked,$value) = @_;
  303:     my $Str = '<input type="radio" name="'.$name.'" ';
  304:     if (defined($value)) {
  305:         $Str .= 'value="'.$value.'"';
  306:     } 
  307:     if ($checked eq $value) {
  308:         $Str .= ' checked="1"';
  309:     }
  310:     $Str .= ' />';
  311:     return $Str;
  312: }
  313: 
  314: ##############################################
  315: ##############################################
  316: 
  317: =pod
  318: 
  319: =item &date_setter
  320: 
  321: &date_setter returns html and javascript for a compact date-setting form.
  322: To retrieve values from it, use &get_date_from_form().
  323: 
  324: Inputs
  325: 
  326: =over 4
  327: 
  328: =item $dname 
  329: 
  330: The name to prepend to the form elements.  
  331: The form elements defined will be dname_year, dname_month, dname_day,
  332: dname_hour, dname_min, and dname_sec.
  333: 
  334: =item $currentvalue
  335: 
  336: The current setting for this time parameter.  A unix format time
  337: (time in seconds since the beginning of Jan 1st, 1970, GMT.  
  338: An undefined value is taken to indicate the value is the current time.
  339: Also, to be explicit, a value of 'now' also indicates the current time.
  340: 
  341: =item $special
  342: 
  343: Additional html/javascript to be associated with each element in
  344: the date_setter.  See lonparmset for example usage.
  345: 
  346: =item $includeempty 
  347: 
  348: =item $state
  349: 
  350: Specifies the initial state of the form elements.  Either 'disabled' or empty.
  351: Defaults to empty, which indiciates the form elements are not disabled. 
  352: 
  353: =back
  354: 
  355: Bugs
  356: 
  357: The method used to restrict user input will fail in the year 2400.
  358: 
  359: =cut
  360: 
  361: ##############################################
  362: ##############################################
  363: sub date_setter {
  364:     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
  365:         $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
  366:     my $now = time;
  367:     my $wasdefined=1;
  368:     if (! defined($state) || $state ne 'disabled') {
  369:         $state = '';
  370:     }
  371:     if (! defined($no_hh_mm_ss)) {
  372:         $no_hh_mm_ss = 0;
  373:     }
  374:     if ($currentvalue eq 'now') {
  375: 	$currentvalue = $now;
  376:     }
  377:     if ((!defined($currentvalue)) || ($currentvalue eq '')) {
  378: 	$wasdefined=0;
  379: 	if ($includeempty) {
  380: 	    $currentvalue = 0;
  381: 	} else {
  382: 	    $currentvalue = $now;
  383: 	}
  384:     }
  385:     # other potentially useful values:     wkday,yrday,is_daylight_savings
  386:     my $tzname;
  387:     my ($sec,$min,$hour,$mday,$month,$year)=('','',undef,'','','');
  388:     if ($currentvalue) {
  389:         ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue); 
  390:     }
  391:     unless ($wasdefined) {
  392:         ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($now);
  393: 	if (($defhour) || ($defmin) || ($defsec)) {
  394: 	    $sec=($defsec?$defsec:0);
  395: 	    $min=($defmin?$defmin:0);
  396: 	    $hour=($defhour?$defhour:0);
  397: 	} elsif (!$includeempty) {
  398: 	    $sec=0;
  399: 	    $min=0;
  400: 	    $hour=0;
  401: 	}
  402:     }
  403:     my $result = "\n<!-- $dname date setting form -->\n";
  404:     $result .= <<ENDJS;
  405: <script type="text/javascript">
  406:     function $dname\_checkday() {
  407:         var day   = document.$formname.$dname\_day.value;
  408:         var month = document.$formname.$dname\_month.value;
  409:         var year  = document.$formname.$dname\_year.value;
  410:         var valid = true;
  411:         if (day < 1) {
  412:             document.$formname.$dname\_day.value = 1;
  413:         } 
  414:         if (day > 31) {
  415:             document.$formname.$dname\_day.value = 31;
  416:         }
  417:         if ((month == 1)  || (month == 3)  || (month == 5)  ||
  418:             (month == 7)  || (month == 8)  || (month == 10) ||
  419:             (month == 12)) {
  420:             if (day > 31) {
  421:                 document.$formname.$dname\_day.value = 31;
  422:                 day = 31;
  423:             }
  424:         } else if (month == 2 ) {
  425:             if ((year % 4 == 0) && (year % 100 != 0)) {
  426:                 if (day > 29) {
  427:                     document.$formname.$dname\_day.value = 29;
  428:                 }
  429:             } else if (day > 29) {
  430:                 document.$formname.$dname\_day.value = 28;
  431:             }
  432:         } else if (day > 30) {
  433:             document.$formname.$dname\_day.value = 30;
  434:         }
  435:     }
  436:     
  437:     function $dname\_disable() {
  438:         document.$formname.$dname\_month.disabled=true;
  439:         document.$formname.$dname\_day.disabled=true;
  440:         document.$formname.$dname\_year.disabled=true;
  441:         document.$formname.$dname\_hour.disabled=true;
  442:         document.$formname.$dname\_minute.disabled=true;
  443:         document.$formname.$dname\_second.disabled=true;
  444:     }
  445: 
  446:     function $dname\_enable() {
  447:         document.$formname.$dname\_month.disabled=false;
  448:         document.$formname.$dname\_day.disabled=false;
  449:         document.$formname.$dname\_year.disabled=false;
  450:         document.$formname.$dname\_hour.disabled=false;
  451:         document.$formname.$dname\_minute.disabled=false;
  452:         document.$formname.$dname\_second.disabled=false;        
  453:     }
  454: 
  455:     function $dname\_opencalendar() {
  456:         if (! document.$formname.$dname\_month.disabled) {
  457:             var calwin=window.open(
  458: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
  459: document.$formname.$dname\_month.value+"&year="+
  460: document.$formname.$dname\_year.value,
  461:              "LONCAPAcal",
  462:               "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
  463:         }
  464: 
  465:     }
  466: </script>
  467: ENDJS
  468:     $result .= '  <span style="white-space: nowrap;">';
  469:     my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
  470:     # Month
  471:     my @Months = qw/January February  March     April   May      June 
  472:                     July    August    September October November December/;
  473:     # Pad @Months with a bogus value to make indexing easier
  474:     unshift(@Months,'If you can read this an error occurred');
  475:     if ($includeempty) { $monthselector.="<option value=''></option>"; }
  476:     for(my $m = 1;$m <=$#Months;$m++) {
  477:         $monthselector .= qq{      <option value="$m" };
  478:         $monthselector .= "selected " if ($m-1 eq $month);
  479:         $monthselector .= '> '.&mt($Months[$m]).' </option>';
  480:     }
  481:     $monthselector.= '  </select>';
  482:     # Day
  483:     my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
  484:     # Year
  485:     my $yearselector = qq{<input type="year" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
  486:     #
  487:     my $hourselector = qq{<select name="$dname\_hour" $special $state >};
  488:     if ($includeempty) { 
  489:         $hourselector.=qq{<option value=''></option>};
  490:     }
  491:     for (my $h = 0;$h<24;$h++) {
  492:         $hourselector .= qq{<option value="$h" };
  493:         $hourselector .= "selected " if (defined($hour) && $hour == $h);
  494:         $hourselector .= ">";
  495:         my $timest='';
  496:         if ($h == 0) {
  497:             $timest .= "12 am";
  498:         } elsif($h == 12) {
  499:             $timest .= "12 noon";
  500:         } elsif($h < 12) {
  501:             $timest .= "$h am";
  502:         } else {
  503:             $timest .= $h-12 ." pm";
  504:         }
  505:         $timest=&mt($timest);
  506:         $hourselector .= $timest." </option>\n";
  507:     }
  508:     $hourselector .= "  </select>\n";
  509:     my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
  510:     my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
  511:     my $cal_link;
  512:     if (!$nolink) {
  513:         $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
  514:     }
  515:     #
  516:     my $tzone = ' '.$tzname.' ';
  517:     if ($no_hh_mm_ss) {
  518:         $result .= &mt('[_1] [_2] [_3] ',
  519:                        $monthselector,$dayselector,$yearselector).
  520:                    $tzone;
  521:         if (!$nolink) {
  522:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  523:         }
  524:     } else {
  525:         $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
  526:                       $monthselector,$dayselector,$yearselector,
  527:                       $hourselector,$minuteselector,$secondselector).
  528:                    $tzone;
  529:         if (!$nolink) {
  530:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  531:         }
  532:     }
  533:     $result .= "</span>\n<!-- end $dname date setting form -->\n";
  534:     return $result;
  535: }
  536: 
  537: sub get_timedates {
  538:     my ($epoch) = @_;
  539:     my $dt = DateTime->from_epoch(epoch => $epoch)
  540:                      ->set_time_zone(&Apache::lonlocal::gettimezone());
  541:     my $tzname = $dt->time_zone_short_name();
  542:     my $sec = $dt->second;
  543:     my $min = $dt->minute;
  544:     my $hour = $dt->hour;
  545:     my $mday = $dt->day;
  546:     my $month = $dt->month;
  547:     if ($month) {
  548:         $month --;
  549:     }
  550:     my $year = $dt->year;
  551:     return ($tzname,$sec,$min,$hour,$mday,$month,$year);
  552: }
  553: 
  554: sub build_url {
  555:     my ($base, $fields)=@_;
  556:     my $url;
  557:     $url = $base.'?';
  558:     foreach my $key (keys(%$fields)) {
  559:         $url.=&escape($key).'='.&escape($$fields{$key}).'&amp;';
  560:     }
  561:     $url =~ s/&amp;$//;
  562:     return $url;
  563: }
  564: 
  565: 
  566: ##############################################
  567: ##############################################
  568: 
  569: =pod
  570: 
  571: =item &get_date_from_form
  572: 
  573: get_date_from_form retrieves the date specified in an &date_setter form.
  574: 
  575: Inputs:
  576: 
  577: =over 4
  578: 
  579: =item $dname
  580: 
  581: The name passed to &datesetter, which prefixes the form elements.
  582: 
  583: =item $defaulttime
  584: 
  585: The unix time to use as the default in case of poor inputs.
  586: 
  587: =back
  588: 
  589: Returns: Unix time represented in the form.
  590: 
  591: =cut
  592: 
  593: ##############################################
  594: ##############################################
  595: sub get_date_from_form {
  596:     my ($dname) = @_;
  597:     my ($sec,$min,$hour,$day,$month,$year);
  598:     #
  599:     if (defined($env{'form.'.$dname.'_second'})) {
  600:         my $tmpsec = $env{'form.'.$dname.'_second'};
  601:         if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
  602:             $sec = $tmpsec;
  603:         }
  604: 	if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
  605:     } else {
  606:         $sec = 0;
  607:     }
  608:     if (defined($env{'form.'.$dname.'_minute'})) {
  609:         my $tmpmin = $env{'form.'.$dname.'_minute'};
  610:         if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
  611:             $min = $tmpmin;
  612:         }
  613: 	if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
  614:     } else {
  615:         $min = 0;
  616:     }
  617:     if (defined($env{'form.'.$dname.'_hour'})) {
  618:         my $tmphour = $env{'form.'.$dname.'_hour'};
  619:         if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
  620:             $hour = $tmphour;
  621:         }
  622:     } else {
  623:         $hour = 0;
  624:     }
  625:     if (defined($env{'form.'.$dname.'_day'})) {
  626:         my $tmpday = $env{'form.'.$dname.'_day'};
  627:         if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
  628:             $day = $tmpday;
  629:         }
  630:     }
  631:     if (defined($env{'form.'.$dname.'_month'})) {
  632:         my $tmpmonth = $env{'form.'.$dname.'_month'};
  633:         if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
  634:             $month = $tmpmonth;
  635:         }
  636:     }
  637:     if (defined($env{'form.'.$dname.'_year'})) {
  638:         my $tmpyear = $env{'form.'.$dname.'_year'};
  639:         if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
  640:             $year = $tmpyear;
  641:         }
  642:     }
  643:     if (($year<1970) || ($year>2037)) { return undef; }
  644:     if (defined($sec) && defined($min)   && defined($hour) &&
  645:         defined($day) && defined($month) && defined($year)) {
  646:         my $timezone = &Apache::lonlocal::gettimezone();
  647:         my $dt = DateTime->new( year   => $year,
  648:                                 month  => $month,
  649:                                 day    => $day,
  650:                                 hour   => $hour,
  651:                                 minute => $min,
  652:                                 second => $sec,
  653:                                 time_zone => $timezone,
  654:                               );
  655:         my $epoch_time  = $dt->epoch;
  656:         if ($epoch_time ne '') {
  657:             return $epoch_time;
  658:         } else {
  659:             return undef;
  660:         }
  661:     } else {
  662:         return undef;
  663:     }
  664: }
  665: 
  666: ##############################################
  667: ##############################################
  668: 
  669: =pod
  670: 
  671: =item &pjump_javascript_definition()
  672: 
  673: Returns javascript defining the 'pjump' function, which opens up a
  674: parameter setting wizard.
  675: 
  676: =cut
  677: 
  678: ##############################################
  679: ##############################################
  680: sub pjump_javascript_definition {
  681:     my $Str = <<END;
  682:     function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
  683:         parmwin=window.open("/adm/rat/parameter.html?type="+escape(type)
  684:                  +"&value="+escape(value)+"&marker="+escape(marker)
  685:                  +"&return="+escape(ret)
  686:                  +"&call="+escape(call)+"&name="+escape(dis)
  687:                  +"&defhour="+escape(hour)+"&defmin="+escape(min)
  688:                  +"&defsec="+escape(sec),"LONCAPAparms",
  689:                  "height=350,width=350,scrollbars=no,menubar=no");
  690:     }
  691: END
  692:     return $Str;
  693: }
  694: 
  695: ##############################################
  696: ##############################################
  697: 
  698: =pod
  699: 
  700: =item &javascript_nothing()
  701: 
  702: Return an appropriate null for the users browser.  This is used
  703: as the first arguement for window.open calls when you want a blank
  704: window that you can then write to.
  705: 
  706: =cut
  707: 
  708: ##############################################
  709: ##############################################
  710: sub javascript_nothing {
  711:     # mozilla and other browsers work with "''", but IE on mac does not.
  712:     my $nothing = "''";
  713:     my $user_browser;
  714:     my $user_os;
  715:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  716:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  717:     if (! defined($user_browser) || ! defined($user_os)) {
  718:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  719:                            &Apache::loncommon::decode_user_agent();
  720:     }
  721:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
  722:         $nothing = "'javascript:void(0);'";
  723:     }
  724:     return $nothing;
  725: }
  726: 
  727: ##############################################
  728: ##############################################
  729: sub javascript_docopen {
  730:     my ($mimetype) = @_;
  731:     $mimetype ||= 'text/html';
  732:     # safari does not understand document.open() and loads "text/html"
  733:     my $nothing = "''";
  734:     my $user_browser;
  735:     my $user_os;
  736:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  737:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  738:     if (! defined($user_browser) || ! defined($user_os)) {
  739:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  740:                            &Apache::loncommon::decode_user_agent();
  741:     }
  742:     if ($user_browser eq 'safari' && $user_os =~ 'mac') {
  743:         $nothing = "document.clear()";
  744:     } else {
  745: 	$nothing = "document.open('$mimetype','replace')";
  746:     }
  747:     return $nothing;
  748: }
  749: 
  750: 
  751: ##############################################
  752: ##############################################
  753: 
  754: =pod
  755: 
  756: =item &StatusOptions()
  757: 
  758: Returns html for a selection box which allows the user to choose the
  759: enrollment status of students.  The selection box name is 'Status'.
  760: 
  761: Inputs:
  762: 
  763: $status: the currently selected status.  If undefined the value of
  764: $env{'form.Status'} is taken.  If that is undefined, a value of 'Active'
  765: is used.
  766: 
  767: $formname: The name of the form.  If defined the onchange attribute of
  768: the selection box is set to document.$formname.submit().
  769: 
  770: $size: the size (number of lines) of the selection box.
  771: 
  772: $onchange: javascript to use when the value is changed.  Enclosed in 
  773: double quotes, ""s, not single quotes.
  774: 
  775: Returns: a perl string as described.
  776: 
  777: =cut
  778: 
  779: ##############################################
  780: ##############################################
  781: sub StatusOptions {
  782:     my ($status, $formName,$size,$onchange,$mult)=@_;
  783:     $size = 1 if (!defined($size));
  784:     if (! defined($status)) {
  785:         $status = 'Active';
  786:         $status = $env{'form.Status'} if (exists($env{'form.Status'}));
  787:     }
  788: 
  789:     my $Str = '';
  790:     $Str .= '<select name="Status"';
  791:     if (defined($mult)){
  792:         $Str .= ' multiple="multiple" ';
  793:     }
  794:     if(defined($formName) && $formName ne '' && ! defined($onchange)) {
  795:         $Str .= ' onchange="document.'.$formName.'.submit()"';
  796:     }
  797:     if (defined($onchange)) {
  798:         $Str .= ' onchange="'.$onchange.'"';
  799:     }
  800:     $Str .= ' size="'.$size.'" ';
  801:     $Str .= '>'."\n";
  802:     foreach my $type (['Active',  &mt('Currently Has Access')],
  803: 		      ['Future',  &mt('Will Have Future Access')],
  804: 		      ['Expired', &mt('Previously Had Access')],
  805: 		      ['Any',     &mt('Any Access Status')]) {
  806: 	my ($name,$label) = @$type;
  807: 	$Str .= '<option value="'.$name.'" ';
  808: 	if ($status eq $name) {
  809: 	    $Str .= 'selected="selected" ';
  810: 	}
  811: 	$Str .= '>'.$label.'</option>'."\n";
  812:     }
  813: 
  814:     $Str .= '</select>'."\n";
  815: }
  816: 
  817: ########################################################
  818: ########################################################
  819: 
  820: =pod
  821: 
  822: =item Progess Window Handling Routines
  823: 
  824: These routines handle the creation, update, increment, and closure of 
  825: progress windows.  The progress window reports to the user the number
  826: of items completed and an estimate of the time required to complete the rest.
  827: 
  828: =over 4
  829: 
  830: 
  831: =item &Create_PrgWin
  832: 
  833: Writes javascript to the client to open a progress window and returns a
  834: data structure used for bookkeeping.
  835: 
  836: Inputs
  837: 
  838: =over 4
  839: 
  840: =item $r Apache request
  841: 
  842: =item $title The title of the progress window
  843: 
  844: =item $heading A description (usually 1 line) of the process being initiated.
  845: 
  846: =item $number_to_do The total number of items being processed.
  847: 
  848: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
  849:        specified)
  850: 
  851: =item $width Specify the width in charaters of the input field.
  852: 
  853: =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
  854: 
  855: =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 
  856: 
  857: =back
  858: 
  859: Returns a hash containing the progress state data structure.
  860: 
  861: 
  862: =item &Update_PrgWin
  863: 
  864: Updates the text in the progress indicator.  Does not increment the count.
  865: See &Increment_PrgWin.
  866: 
  867: Inputs:
  868: 
  869: =over 4
  870: 
  871: =item $r Apache request
  872: 
  873: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
  874: 
  875: =item $displaystring The string to write to the status indicator
  876: 
  877: =back
  878: 
  879: Returns: none
  880: 
  881: 
  882: =item Increment_PrgWin
  883: 
  884: Increment the count of items completed for the progress window by 1.  
  885: 
  886: Inputs:
  887: 
  888: =over 4
  889: 
  890: =item $r Apache request
  891: 
  892: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  893: 
  894: =item $extraInfo A description of the items being iterated over.  Typically
  895: 'student'.
  896: 
  897: =back
  898: 
  899: Returns: none
  900: 
  901: 
  902: =item Close_PrgWin
  903: 
  904: Closes the progress window.
  905: 
  906: Inputs:
  907: 
  908: =over 4 
  909: 
  910: =item $r Apache request
  911: 
  912: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  913: 
  914: =back
  915: 
  916: Returns: none
  917: 
  918: =back
  919: 
  920: =cut
  921: 
  922: ########################################################
  923: ########################################################
  924: 
  925: my $uniq=0;
  926: sub get_uniq_name {
  927:     $uniq++;
  928:     return 'uniquename'.$uniq;
  929: }
  930: 
  931: # Create progress
  932: sub Create_PrgWin {
  933:     my ($r, $title, $heading, $number_to_do,$type,$width,$formname,
  934: 	$inputname)=@_;
  935:     if (!defined($type)) { $type='popup'; }
  936:     if (!defined($width)) { $width=55; }
  937:     my %prog_state;
  938:     $prog_state{'type'}=$type;
  939:     if ($type eq 'popup') {
  940: 	$prog_state{'window'}='popwin';
  941: 	my $start_page =
  942: 	    &Apache::loncommon::start_page($title,undef,
  943: 					   {'only_body' => 1,
  944: 					    'bgcolor'   => '#88DDFF',
  945: 					    'js_ready'  => 1});
  946: 	my $end_page = &Apache::loncommon::end_page({'js_ready'  => 1});
  947: 
  948: 	#the whole function called through timeout is due to issues
  949: 	#in mozilla Read BUG #2665 if you want to know the whole story
  950: 	&r_print($r,'<script type="text/javascript">'.
  951:         "var popwin;
  952:          function openpopwin () {
  953:          popwin=open(\'\',\'popwin\',\'width=400,height=100\');".
  954:         "popwin.document.writeln(\'".$start_page.
  955:               "<h4>".&mt("$heading")."<\/h4>".
  956:               "<form action= \"\" name=\"popremain\" method=\"post\">".
  957:               '<input type="text" size="'.$width.'" name="remaining" value="'.
  958: 	      &mt('Starting').'" /><\\/form>'.$end_page.
  959:               "\');".
  960:         "popwin.document.close();}".
  961:         "\nwindow.setTimeout(openpopwin,0)</script>");
  962: 	$prog_state{'formname'}='popremain';
  963: 	$prog_state{'inputname'}="remaining";
  964:     } elsif ($type eq 'inline') {
  965: 	$prog_state{'window'}='window';
  966: 	if (!$formname) {
  967: 	    $prog_state{'formname'}=&get_uniq_name();
  968: 	    &r_print($r,'<form action="" name="'.$prog_state{'formname'}.'">');
  969: 	} else {
  970: 	    $prog_state{'formname'}=$formname;
  971: 	}
  972: 	if (!$inputname) {
  973: 	    $prog_state{'inputname'}=&get_uniq_name();
  974: 	    &r_print($r,&mt("$heading [_1]",' <input type="text" name="'.$prog_state{'inputname'}.'" size="'.$width.'" />'));
  975: 	} else {
  976: 	    $prog_state{'inputname'}=$inputname;
  977: 	    
  978: 	}
  979: 	if (!$formname) { &r_print($r,'</form>'); }
  980: 	&Update_PrgWin($r,\%prog_state,&mt('Starting'));
  981:     }
  982: 
  983:     $prog_state{'done'}=0;
  984:     $prog_state{'firststart'}=&Time::HiRes::time();
  985:     $prog_state{'laststart'}=&Time::HiRes::time();
  986:     $prog_state{'max'}=$number_to_do;
  987:     
  988:     return %prog_state;
  989: }
  990: 
  991: # update progress
  992: sub Update_PrgWin {
  993:     my ($r,$prog_state,$displayString)=@_;
  994:     &r_print($r,'<script type="text/javascript">'.$$prog_state{'window'}.'.document.'.
  995: 	     $$prog_state{'formname'}.'.'.
  996: 	     $$prog_state{'inputname'}.'.value="'.
  997: 	     $displayString.'";</script>');
  998:     $$prog_state{'laststart'}=&Time::HiRes::time();
  999: }
 1000: 
 1001: # increment progress state
 1002: sub Increment_PrgWin {
 1003:     my ($r,$prog_state,$extraInfo)=@_;
 1004:     $$prog_state{'done'}++;
 1005:     my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
 1006:         $$prog_state{'done'} *
 1007: 	($$prog_state{'max'}-$$prog_state{'done'});
 1008:     $time_est = int($time_est);
 1009:     #
 1010:     my $min = int($time_est/60);
 1011:     my $sec = $time_est % 60;
 1012:     # 
 1013:     my $str;
 1014:     if ($min == 0 && $sec > 1) {
 1015:         $str = '[_2] seconds';
 1016:     } elsif ($min == 1 && $sec > 1) {
 1017:         $str = '1 minute [_2] seconds';
 1018:     } elsif ($min == 1 && $sec < 2) {
 1019:         $str = '1 minute';
 1020:     } elsif ($min < 10 && $sec > 1) {
 1021:         $str = '[_1] minutes, [_2] seconds';
 1022:     } elsif ($min >= 10 || $sec < 2) {
 1023:         $str = '[_1] minutes';
 1024:     }
 1025:     $time_est = &mt($str,$min,$sec);
 1026:     #
 1027:     my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
 1028:     if ($lasttime > 9) {
 1029:         $lasttime = int($lasttime);
 1030:     } elsif ($lasttime < 0.01) {
 1031:         $lasttime = 0;
 1032:     } else {
 1033:         $lasttime = sprintf("%3.2f",$lasttime);
 1034:     }
 1035:     if ($lasttime == 1) {
 1036:         $lasttime = '('.$lasttime.' '.&mt('second for').' '.$extraInfo.')';
 1037:     } else {
 1038:         $lasttime = '('.$lasttime.' '.&mt('seconds for').' '.$extraInfo.')';
 1039:     }
 1040:     #
 1041:     my $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
 1042:     my $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
 1043:     if (! defined($user_browser) || ! defined($user_os)) {
 1044:         (undef,$user_browser,undef,undef,undef,$user_os) = 
 1045:                            &Apache::loncommon::decode_user_agent();
 1046:     }
 1047:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
 1048:         $lasttime = '';
 1049:     }
 1050:     &r_print($r,'<script>'.$$prog_state{'window'}.'.document.'.
 1051: 	     $$prog_state{'formname'}.'.'.
 1052: 	     $$prog_state{'inputname'}.'.value="'.
 1053: 	     $$prog_state{'done'}.'/'.$$prog_state{'max'}.
 1054: 	     ': '.$time_est.' '.&mt('remaining').' '.$lasttime.'";'.'</script>');
 1055:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1056: }
 1057: 
 1058: # close Progress Line
 1059: sub Close_PrgWin {
 1060:     my ($r,$prog_state)=@_;
 1061:     if ($$prog_state{'type'} eq 'popup') {
 1062: 	&r_print($r,'<script>popwin.close()</script>'."\n");
 1063:     } elsif ($$prog_state{'type'} eq 'inline') {
 1064: 	&Update_PrgWin($r,$prog_state,&mt('Done'));
 1065:     }
 1066:     undef(%$prog_state);
 1067: }
 1068: 
 1069: sub r_print {
 1070:     my ($r,$to_print)=@_;
 1071:     if ($r) {
 1072: 	$r->print($to_print);
 1073: 	$r->rflush();
 1074:     } else {
 1075: 	print($to_print);
 1076:     }
 1077: }
 1078: 
 1079: # ------------------------------------------------------- Puts directory header
 1080: 
 1081: sub crumbs {
 1082:     my ($uri,$target,$prefix,$form,$size,$noformat,$skiplast)=@_;
 1083:     if (! defined($size)) {
 1084:         $size = '+2';
 1085:     }
 1086:     if ($target) {
 1087:         $target = ' target="'.
 1088:                   &Apache::loncommon::escape_single($target).'"';
 1089:     }
 1090:     my $output='';
 1091:     unless ($noformat) { $output.='<br /><tt><b>'; }
 1092:     $output.='<font size="'.$size.'">'.$prefix.'/';
 1093:     if ($env{'user.adv'}) {
 1094: 	my $path=$prefix.'/';
 1095: 	foreach my $dir (split('/',$uri)) {
 1096:             if (! $dir) { next; }
 1097:             $path .= $dir;
 1098: 	    if ($path eq $uri) {
 1099: 		if ($skiplast) {
 1100: 		    $output.=$dir;
 1101:                     last;
 1102: 		} 
 1103: 	    } else {
 1104: 		$path.='/'; 
 1105: 	    }	    
 1106:             my $href_path = &HTML::Entities::encode($path,'<>&"');
 1107: 	    &Apache::loncommon::inhibit_menu_check(\$href_path);
 1108: 	    if ($form) {
 1109: 	        my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
 1110: 	        $output.=qq{<a href="$href" $target>$dir</a>/};
 1111: 	    } else {
 1112: 	        $output.=qq{<a href="$href_path" $target>$dir</a>/};
 1113: 	    }
 1114: 	}
 1115:     } else {
 1116: 	foreach my $dir (split('/',$uri)) {
 1117:             if (! $dir) { next; }
 1118: 	    $output.=$dir.'/';
 1119: 	}
 1120:     }
 1121:     if ($uri !~ m|/$|) { $output=~s|/$||; }
 1122:     return $output.'</font>'.($noformat?'':'</b></tt><br />');
 1123: }
 1124: 
 1125: # --------------------- A function that generates a window for the spellchecker
 1126: 
 1127: sub spellheader {
 1128:     my $start_page=
 1129: 	&Apache::loncommon::start_page('Speller Suggestions',undef,
 1130: 				       {'only_body'   => 1,
 1131: 					'js_ready'    => 1,
 1132: 					'bgcolor'     => '#DDDDDD',
 1133: 				        'add_entries' => {
 1134: 					    'onload' => 
 1135:                                                'document.forms.spellcheckform.submit()',
 1136:                                              }
 1137: 				        });
 1138:     my $end_page=
 1139: 	&Apache::loncommon::end_page({'js_ready'  => 1}); 
 1140: 
 1141:     my $nothing=&javascript_nothing();
 1142:     return (<<ENDCHECK);
 1143: <script type="text/javascript"> 
 1144: //<!-- BEGIN LON-CAPA Internal
 1145: var checkwin;
 1146: 
 1147: function spellcheckerwindow(string) {
 1148:     var esc_string = string.replace(/\"/g,'&quot;');
 1149:     checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
 1150:     checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
 1151:     checkwin.document.close();
 1152: }
 1153: // END LON-CAPA Internal -->
 1154: </script>
 1155: ENDCHECK
 1156: }
 1157: 
 1158: # ---------------------------------- Generate link to spell checker for a field
 1159: 
 1160: sub spelllink {
 1161:     my ($form,$field)=@_;
 1162:     my $linktext=&mt('Check Spelling');
 1163:     return (<<ENDLINK);
 1164: <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>
 1165: ENDLINK
 1166: }
 1167: 
 1168: # ------------------------------------------------- Output headers for HTMLArea
 1169: 
 1170: {
 1171:     my @htmlareafields;
 1172:     sub init_htmlareafields {
 1173: 	undef(@htmlareafields);
 1174:     }
 1175:     
 1176:     sub add_htmlareafields {
 1177: 	my (@newfields) = @_;
 1178: 	push(@htmlareafields,@newfields);
 1179:     }
 1180: 
 1181:     sub get_htmlareafields {
 1182: 	return @htmlareafields;
 1183:     }
 1184: }
 1185: 
 1186: sub htmlareaheaders {
 1187:     return if (&htmlareablocked());
 1188:     return if (!&htmlareabrowser());
 1189:     return (<<ENDHEADERS);
 1190: <script type="text/javascript" src="/fckeditor/fckeditor.js"></script>
 1191: ENDHEADERS
 1192: }
 1193: 
 1194: # ----------------------------------------------------------------- Preferences
 1195: 
 1196: sub disablelink {
 1197:     my @fields=@_;
 1198:     if (defined($#fields)) {
 1199: 	unless ($#fields>=0) { return ''; }
 1200:     }
 1201:     return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=off&returnurl=','<>&"').&escape($ENV{'REQUEST_URI'}).'">'.&mt('Disable WYSIWYG Editor').'</a>';
 1202: }
 1203: 
 1204: sub enablelink {
 1205:     my @fields=@_;
 1206:     if (defined($#fields)) {
 1207: 	unless ($#fields>=0) { return ''; }
 1208:     }
 1209:     return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=on&returnurl=','<>&"').&escape($ENV{'REQUEST_URI'}).'">'.&mt('Enable WYSIWYG Editor').'</a>';
 1210: }
 1211: 
 1212: # ------------------------------------------------- lang to use in html editor
 1213: sub htmlarea_lang {
 1214:     my $lang='en';
 1215:     if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
 1216: 	$lang=&mt('htmlarea_lang');
 1217:     }
 1218:     return $lang;
 1219: }
 1220: 
 1221: # ----------------------------------------- Script to activate only some fields
 1222: 
 1223: sub htmlareaselectactive {
 1224:     my @fields=@_;
 1225:     unless (&htmlareabrowser()) { return ''; }
 1226:     if (&htmlareablocked()) { return '<br />'.&enablelink(@fields); }
 1227:     my $output='<script type="text/javascript" defer="1">';
 1228:     my $lang = &htmlarea_lang();
 1229:     foreach my $field (@fields) {
 1230: 	$output.="
 1231: {
 1232:     var oFCKeditor = new FCKeditor('$field');
 1233:     oFCKeditor.Config['CustomConfigurationsPath'] = 
 1234: 	'/fckeditor/loncapaconfig.js';    
 1235:     oFCKeditor.ReplaceTextarea();
 1236:     oFCKeditor.Config['AutoDetectLanguage'] = false;
 1237:     oFCKeditor.Config['DefaultLanguage'] = '$lang';
 1238: }";
 1239:     }
 1240:     $output.="\nwindow.status='Activated Editfields';\n</script><br />".
 1241: 	&disablelink(@fields);
 1242:     return $output;
 1243: }
 1244: 
 1245: # --------------------------------------------------------------------- Blocked
 1246: 
 1247: sub htmlareablocked {
 1248:     unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
 1249:     return 0;
 1250: }
 1251: 
 1252: # ---------------------------------------- Browser capable of running HTMLArea?
 1253: 
 1254: sub htmlareabrowser {
 1255:     return 1;
 1256: }
 1257: 
 1258: ############################################################
 1259: ############################################################
 1260: 
 1261: =pod
 1262: 
 1263: =item breadcrumbs
 1264: 
 1265: Compiles the previously registered breadcrumbs into an series of links.
 1266: FAQ and BUG links will be placed on the left side of the table if they
 1267: are defined for the last registered breadcrumb.  
 1268: Additionally supports a 'component', which will be displayed on the
 1269: right side of the table (without a link).
 1270: A link to help for the component will be included if one is specified.
 1271: 
 1272: All inputs can be undef without problems.
 1273: 
 1274: Inputs: $component (the large text on the right side of the table),
 1275:         $component_help
 1276:         $menulink (boolean, controls whether to include a link to /adm/menu)
 1277:         $helplink (if 'nohelp' don't include the orange help link)
 1278:         $css_class (optional name for the class to apply to the table for CSS)
 1279: Returns a string containing breadcrumbs for the current page.
 1280: 
 1281: =item clear_breadcrumbs
 1282: 
 1283: Clears the previously stored breadcrumbs.
 1284: 
 1285: =item add_breadcrumb
 1286: 
 1287: Pushes a breadcrumb on the stack of crumbs.
 1288: 
 1289: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
 1290: are required.  If present the keys 'faq' and 'bug' will be used to provide
 1291: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' 
 1292: and 'text' values won't be sent through &mt()
 1293: 
 1294: returns: nothing    
 1295: 
 1296: =cut
 1297: 
 1298: ############################################################
 1299: ############################################################
 1300: {
 1301:     my @Crumbs;
 1302:     
 1303:     sub breadcrumbs {
 1304:         my ($component,$component_help,$menulink,$helplink,$css_class) = @_;
 1305:         #
 1306: 	$css_class ||= 'LC_breadcrumbs';
 1307:         my $Str = "\n".'<table class="'.$css_class.'"><tr><td>';
 1308:         #
 1309:         # Make the faq and bug data cascade
 1310:         my $faq = '';
 1311:         my $bug = '';
 1312: 	my $help='';
 1313:         # The last breadcrumb does not have a link, so handle it separately.
 1314:         my $last = pop(@Crumbs);
 1315:         #
 1316:         # The first one should be the course or a menu link
 1317: 	if (!defined($menulink)) { $menulink=1; }
 1318:         if ($menulink) {
 1319:             my $description = 'Menu';
 1320:             my $no_mt_descr = 0;
 1321:             if (exists($env{'request.course.id'}) && 
 1322:                 $env{'request.course.id'} ne '') {
 1323:                 $description = 
 1324:                     $env{'course.'.$env{'request.course.id'}.'.description'};
 1325:                 $no_mt_descr = 1;
 1326:             }
 1327:             unshift(@Crumbs,{
 1328:                     href   =>'/adm/menu',
 1329:                     title  =>'Go to main menu',
 1330:                     target =>'_top',
 1331:                     text   =>$description,
 1332:                     no_mt  =>$no_mt_descr,
 1333:                 });
 1334:         }
 1335:         my $links .= 
 1336:             join('-&gt;',
 1337:                  map {
 1338:                      $faq = $_->{'faq'} if (exists($_->{'faq'}));
 1339:                      $bug = $_->{'bug'} if (exists($_->{'bug'}));
 1340:                      $help = $_->{'help'} if (exists($_->{'help'}));
 1341:                      my $result = '<a href="'.$_->{'href'}.'" ';
 1342:                      if (defined($_->{'target'}) && $_->{'target'} ne '') {
 1343:                          $result .= 'target="'.$_->{'target'}.'" ';
 1344:                      }
 1345: 		     if ($_->{'no_mt'}) {
 1346: 			 $result .='title="'.$_->{'title'}.'">'.
 1347: 			     $_->{'text'}.'</a>';
 1348: 		     } else {
 1349: 			 $result .='title="'.&mt($_->{'title'}).'">'.
 1350: 			     &mt($_->{'text'}).'</a>';
 1351: 		     }
 1352:                      $result;
 1353:                      } @Crumbs
 1354:                  );
 1355:         $links .= '-&gt;' if ($links ne '');
 1356: 	if ($last->{'no_mt'}) {
 1357: 	    $links .= '<b>'.$last->{'text'}.'</b>';
 1358: 	} else {
 1359: 	    $links .= '<b>'.&mt($last->{'text'}).'</b>';
 1360: 	}
 1361:         #
 1362:         my $icons = '';
 1363:         $faq = $last->{'faq'} if (exists($last->{'faq'}));
 1364:         $bug = $last->{'bug'} if (exists($last->{'bug'}));
 1365:         $help = $last->{'help'} if (exists($last->{'help'}));
 1366:         $component_help=($component_help?$component_help:$help);
 1367: #        if ($faq ne '') {
 1368: #            $icons .= &Apache::loncommon::help_open_faq($faq);
 1369: #        }
 1370: #        if ($bug ne '') {
 1371: #            $icons .= &Apache::loncommon::help_open_bug($bug);
 1372: #        }
 1373: 	if ($faq ne '' || $component_help ne '' || $bug ne '') {
 1374: 	    $icons .= &Apache::loncommon::help_open_menu($component,
 1375: 							 $component_help,
 1376: 							 $faq,$bug);
 1377: 	}
 1378:         #
 1379:         $Str .= $links.'</td>';
 1380:         #
 1381:         if (defined($component)) {
 1382:             $Str .= '<td class="'.$css_class.'_component">'.
 1383:                 &mt($component);
 1384: 	    if ($icons ne '') {
 1385: 		$Str .= '&nbsp;'.$icons;
 1386: 	    }
 1387: 	    $Str .= '</td>';
 1388:         }
 1389:         $Str .= '</tr></table>'."\n";
 1390:         #
 1391:         # Return the @Crumbs stack to what we started with
 1392:         push(@Crumbs,$last);
 1393:         shift(@Crumbs);
 1394:         #
 1395:         return $Str;
 1396:     }
 1397: 
 1398:     sub clear_breadcrumbs {
 1399:         undef(@Crumbs);
 1400:     }
 1401: 
 1402:     sub add_breadcrumb {
 1403:         push (@Crumbs,@_);
 1404:     }
 1405: 
 1406: } # End of scope for @Crumbs
 1407: 
 1408: ############################################################
 1409: ############################################################
 1410: 
 1411: # Nested table routines.
 1412: #
 1413: # Routines to display form items in a multi-row table with 2 columns.
 1414: # Uses nested tables to divide form elements into segments.
 1415: # For examples of use see loncom/interface/lonnotify.pm 
 1416: #
 1417: # Can be used in following order: ...
 1418: # &start_pick_box()
 1419: # row1
 1420: # row2
 1421: # row3   ... etc.
 1422: # &submit_row()
 1423: # &end_pick_box()
 1424: #
 1425: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
 1426: # &status_select_row and &email_default_row
 1427: #
 1428: # Can also be used in following order:
 1429: #
 1430: # &start_pick_box()
 1431: # &row_title()
 1432: # &row_closure()
 1433: # &row_title()
 1434: # &row_closure()  ... etc.
 1435: # &submit_row()
 1436: # &end_pick_box()
 1437: #
 1438: # In general a &submit_row() call should proceed the call to &end_pick_box(),
 1439: # as this routine adds a button for form submission.
 1440: # &submit_row() does not require a &row_closure after it.
 1441: #  
 1442: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
 1443: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
 1444: #
 1445: # &row_title() adds a title in the left column for each segment.
 1446: # &row_closure() closes a row with a 1-pixel wide black line.
 1447: #
 1448: # &role_select_row() provides a select box from which to choose 1 or more roles 
 1449: # &course_select_row provides ways of picking groups of courses
 1450: #    radio buttons: all, by category or by picking from a course picker pop-up
 1451: #      note: by category option is only displayed if a domain has implemented 
 1452: #                selection by year, semester, department, number etc.
 1453: #
 1454: # &status_select_row() provides a select box from which to choose 1 or more
 1455: #  access types (current access, prior access, and future access)  
 1456: #
 1457: # &email_default_row() provides text boxes for default e-mail suffixes for
 1458: #  different authentication types in a domain.
 1459: #
 1460: # &row_title() and &row_closure() are called internally by the &*_select_row
 1461: # routines, but can also be called directly to start and end rows which have 
 1462: # needs that are not accommodated by the *_select_row() routines.    
 1463: 
 1464: sub start_pick_box {
 1465:     my ($css_class) = @_;
 1466:     if (defined($css_class)) {
 1467: 	$css_class = 'class="'.$css_class.'"';
 1468:     } else {
 1469: 	$css_class= 'class="LC_pick_box"';
 1470:     }
 1471:     my $output = <<"END";
 1472:  <table $css_class>
 1473: END
 1474:     return $output;
 1475: }
 1476: 
 1477: sub end_pick_box {
 1478:     my $output = <<"END";
 1479:        </table>
 1480: END
 1481:     return $output;
 1482: }
 1483: 
 1484: sub row_title {
 1485:     my ($title,$css_title_class,$css_value_class) = @_;
 1486:     $css_title_class ||= 'LC_pick_box_title';
 1487:     $css_title_class = 'class="'.$css_title_class.'"';
 1488: 
 1489:     $css_value_class ||= 'LC_pick_box_value';
 1490:     $css_value_class = 'class="'.$css_value_class.'"';
 1491: 
 1492:     if ($title ne '') {
 1493:         $title .= ':';
 1494:     }
 1495:     my $output = <<"ENDONE";
 1496:            <tr class="LC_pick_box_row">
 1497:             <td $css_title_class>
 1498: 	       $title
 1499:             </td>
 1500:             <td $css_value_class>
 1501: ENDONE
 1502:     return $output;
 1503: }
 1504: 
 1505: sub row_closure {
 1506:     my ($no_separator) =@_;
 1507:     my $output = <<"ENDTWO";
 1508:             </td>
 1509:            </tr>
 1510: ENDTWO
 1511:     if (!$no_separator) {
 1512:         $output .= <<"ENDTWO";
 1513:            <tr>
 1514:             <td colspan="2" class="LC_pick_box_separator">
 1515:             </td>
 1516:            </tr>
 1517: ENDTWO
 1518:     }
 1519:     return $output;
 1520: }
 1521: 
 1522: sub role_select_row {
 1523:     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
 1524:     my $output;
 1525:     if (defined($title)) {
 1526:         $output = &row_title($title,$css_class);
 1527:     }
 1528:     $output .= qq|
 1529:                                   <select name="roles" multiple >\n|;
 1530:     foreach my $role (@$roles) {
 1531:         my $plrole;
 1532:         if ($role eq 'ow') {
 1533:             $plrole = &mt('Course Owner');
 1534:         } elsif ($role eq 'cr') {
 1535:             if ($show_separate_custom) {
 1536:                 if ($cdom ne '' && $cnum ne '') {
 1537:                     my %course_customroles = &course_custom_roles($cdom,$cnum);
 1538:                     foreach my $crrole (sort(keys(%course_customroles))) {
 1539:                         my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
 1540:                         $output .= '  <option value="'.$crrole.'">'.$plcrrole.
 1541:                                    '</option>';
 1542:                     }
 1543:                 }
 1544:             } else {
 1545:                 $plrole = &mt('Custom Role');
 1546:             }
 1547:         } else {
 1548:             $plrole=&Apache::lonnet::plaintext($role);
 1549:         }
 1550:         if (($role ne 'cr') || (!$show_separate_custom)) {
 1551:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1552:         }
 1553:     }
 1554:     $output .= qq|                </select>\n|;
 1555:     if (defined($title)) {
 1556:         $output .= &row_closure();
 1557:     }
 1558:     return $output;
 1559: }
 1560: 
 1561: sub course_select_row {
 1562:     my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 1563: 	$css_class) = @_;
 1564:     my $output = &row_title($title,$css_class);
 1565:     $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles);
 1566:     $output .= &row_closure();
 1567:     return $output;
 1568: }
 1569: 
 1570: sub course_selection {
 1571:     my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles) = @_;
 1572:     my $output = qq|
 1573: <script type="text/javascript">
 1574:     function coursePick (formname) {
 1575:         for  (var i=0; i<formname.coursepick.length; i++) {
 1576:             if (formname.coursepick[i].value == 'category') {
 1577:                 courseSet('');
 1578:             }
 1579:             if (!formname.coursepick[i].checked) {
 1580:                 if (formname.coursepick[i].value == 'specific') {
 1581:                     formname.coursetotal.value = 0;
 1582:                     formname.courselist = '';
 1583:                 }
 1584:             }
 1585:         }
 1586:     }
 1587:     function setPick (formname) {
 1588:         for  (var i=0; i<formname.coursepick.length; i++) {
 1589:             if (formname.coursepick[i].value == 'category') {
 1590:                 formname.coursepick[i].checked = true;
 1591:             }
 1592:             formname.coursetotal.value = 0;
 1593:             formname.courselist = '';
 1594:         }
 1595:     }
 1596: </script>
 1597:     |;
 1598:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
 1599:                      ($formname,'pickcourse','pickdomain','coursedesc','',1).'</b>';
 1600:         $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.&mt('All courses').'<br />';
 1601:     if ($totcodes > 0) {
 1602:         my $numtitles = @$codetitles;
 1603:         if ($numtitles > 0) {
 1604:             $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 />';
 1605:             $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
 1606:                '<select name="'.$$codetitles[0].
 1607:                '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
 1608:                ' <option value="-1" />Select'."\n";
 1609:             my @items = ();
 1610:             my @longitems = ();
 1611:             if ($$idlist{$$codetitles[0]} =~ /","/) {
 1612:                 @items = split(/","/,$$idlist{$$codetitles[0]});
 1613:             } else {
 1614:                 $items[0] = $$idlist{$$codetitles[0]};
 1615:             }
 1616:             if (defined($$idlist_titles{$$codetitles[0]})) {
 1617:                 if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
 1618:                     @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
 1619:                 } else {
 1620:                     $longitems[0] = $$idlist_titles{$$codetitles[0]};
 1621:                 }
 1622:                 for (my $i=0; $i<@longitems; $i++) {
 1623:                     if ($longitems[$i] eq '') {
 1624:                         $longitems[$i] = $items[$i];
 1625:                     }
 1626:                 }
 1627:             } else {
 1628:                 @longitems = @items;
 1629:             }
 1630:             for (my $i=0; $i<@items; $i++) {
 1631:                 $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
 1632:             }
 1633:             $output .= '</select></td>';
 1634:             for (my $i=1; $i<$numtitles; $i++) {
 1635:                 $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
 1636:                           '<select name="'.$$codetitles[$i].
 1637:                           '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
 1638:                           '<option value="-1">&lt;-Pick '.$$codetitles[$i-1].'</option>'."\n".
 1639:                           '</select>'."\n".
 1640:                           '</td>';
 1641:             }
 1642:             $output .= '</tr></table><br />';
 1643:         }
 1644:     }
 1645:     $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1'".')" />'.&mt('Pick specific course(s):').' '.$courseform.'&nbsp;&nbsp;<input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
 1646:     return $output;
 1647: }
 1648: 
 1649: sub status_select_row {
 1650:     my ($types,$title,$css_class) = @_;
 1651:     my $output; 
 1652:     if (defined($title)) {
 1653:         $output = &row_title($title,$css_class,'LC_pick_box_select');
 1654:     }
 1655:     $output .= qq|
 1656:                                     <select name="types" multiple>\n|;
 1657:     foreach my $status_type (sort(keys(%{$types}))) {
 1658:         $output .= '  <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
 1659:     }
 1660:     $output .= qq|                   </select>\n|; 
 1661:     if (defined($title)) {
 1662:         $output .= &row_closure();
 1663:     }
 1664:     return $output;
 1665: }
 1666: 
 1667: sub email_default_row {
 1668:     my ($authtypes,$title,$descrip,$css_class) = @_;
 1669:     my $output = &row_title($title,$css_class);
 1670:     $output .= $descrip.
 1671: 	&Apache::loncommon::start_data_table().
 1672: 	&Apache::loncommon::start_data_table_header_row().
 1673: 	'<th>'.&mt('Authentication Method').'</th>'.
 1674: 	'<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
 1675: 	&Apache::loncommon::end_data_table_header_row();
 1676:     my $rownum = 0;
 1677:     foreach my $auth (sort(keys(%{$authtypes}))) {
 1678:         my ($userentry,$size);
 1679:         if ($auth =~ /^krb/) {
 1680:             $userentry = '';
 1681:             $size = 25;
 1682:         } else {
 1683:             $userentry = 'username@';
 1684:             $size = 15;
 1685:         }
 1686:         $output .= &Apache::loncommon::start_data_table_row().
 1687: 	    '<td>  '.$$authtypes{$auth}.'</td>'.
 1688: 	    '<td align="right">'.$userentry.
 1689: 	    '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
 1690: 	    &Apache::loncommon::end_data_table_row();
 1691:     }
 1692:     $output .= &Apache::loncommon::end_data_table();
 1693:     $output .= &row_closure();
 1694:     return $output;
 1695: }
 1696: 
 1697: 
 1698: sub submit_row {
 1699:     my ($title,$cmd,$submit_text,$css_class) = @_;
 1700:     my $output = &row_title($title,$css_class,'LC_pick_box_submit');
 1701:     $output .= qq|
 1702:              <br />
 1703:              <input type="hidden" name="command" value="$cmd" />
 1704:              <input type="submit" value="$submit_text"/> &nbsp;
 1705:              <br /><br />
 1706:             \n|;
 1707:     return $output;
 1708: }
 1709: 
 1710: sub course_custom_roles {
 1711:     my ($cdom,$cnum) = @_;
 1712:     my %returnhash=();
 1713:     my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 1714:     foreach my $person (sort(keys(%coursepersonnel))) {
 1715:         my ($role) = ($person =~ /^([^:]+):/);
 1716:         my ($end,$start) = split(/:/,$coursepersonnel{$person});
 1717:         if ($end == -1 && $start == -1) {
 1718:             next;
 1719:         }
 1720:         if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
 1721:             $returnhash{$role} ++;
 1722:         }
 1723:     }
 1724:     return %returnhash;
 1725: }
 1726: 
 1727: 
 1728: ##############################################
 1729: ##############################################
 1730:                                                                              
 1731: # echo_form_input
 1732: #
 1733: # Generates html markup to add form elements from the referrer page
 1734: # as hidden form elements (values encoded) in the new page.
 1735: #
 1736: # Intended to support two types of use 
 1737: # (a) to allow backing up to earlier pages in a multi-page 
 1738: # form submission process using a breadcrumb trail.
 1739: #
 1740: # (b) to allow the current page to be reloaded with form elements
 1741: # set on previous page to remain unchanged.  An example would
 1742: # be where the a page containing a dynamically-built table of data is 
 1743: # is to be redisplayed, with only the sort order of the data changed. 
 1744: #  
 1745: # Inputs:
 1746: # 1. Reference to array of form elements in the submitted form on 
 1747: # the referrer page which are to be excluded from the echoed elements.
 1748: #
 1749: # 2. Reference to array of regular expressions, which if matched in the  
 1750: # name of the form element n the referrer page will be omitted from echo. 
 1751: #
 1752: # Outputs: A scalar containing the html markup for the echoed form
 1753: # elements (all as hidden elements, with values encoded). 
 1754: 
 1755: 
 1756: sub echo_form_input {
 1757:     my ($excluded,$regexps) = @_;
 1758:     my $output = '';
 1759:     foreach my $key (keys(%env)) {
 1760:         if ($key =~ /^form\.(.+)$/) {
 1761:             my $name = $1;
 1762:             my $match = 0;
 1763:             if ((!@{$excluded}) || (!grep/^$name$/,@{$excluded})) {
 1764:                 if (defined($regexps)) {
 1765:                     if (@{$regexps} > 0) {
 1766:                         foreach my $regexp (@{$regexps}) {
 1767:                             if ($name =~ /\Q$regexp\E/) {
 1768:                                 $match = 1;
 1769:                                 last;
 1770:                             }
 1771:                         }
 1772:                     }
 1773:                 }
 1774:                 if (!$match) {
 1775:                     if (ref($env{$key})) {
 1776:                         foreach my $value (@{$env{$key}}) {
 1777:                             $value = &HTML::Entities::encode($value,'<>&"');
 1778:                             $output .= '<input type="hidden" name="'.$name.
 1779:                                              '" value="'.$value.'" />'."\n";
 1780:                         }
 1781:                     } else {
 1782:                         my $value = &HTML::Entities::encode($env{$key},'<>&"');
 1783:                         $output .= '<input type="hidden" name="'.$name.
 1784:                                              '" value="'.$value.'" />'."\n";
 1785:                     }
 1786:                 }
 1787:             }
 1788:         }
 1789:     }
 1790:     return $output;
 1791: }
 1792: 
 1793: ##############################################
 1794: ##############################################
 1795:                                                                              
 1796: # set_form_elements
 1797: #
 1798: # Generates javascript to set form elements to values based on
 1799: # corresponding values for the same form elements when the page was
 1800: # previously submitted.
 1801: #     
 1802: # Last submission values are read from hidden form elements in referring 
 1803: # page which have the same name, i.e., generated by &echo_form_input(). 
 1804: #
 1805: # Intended to be called by onload event.
 1806: #
 1807: # Inputs:
 1808: # (a) Reference to hash of echoed form elements to be set.
 1809: #
 1810: # In the hash, keys are the form element names, and the values are the
 1811: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
 1812: # hidden).
 1813: #
 1814: # (b) Optional reference to hash of stored elements to be set.
 1815: #
 1816: # If the page being displayed is a page which permits modification of
 1817: # previously stored data, e.g., the first page in a multi-page submission,
 1818: # then if stored is supplied, form elements will be set to the last stored
 1819: # values.  If user supplied values are also available for the same elements
 1820: # these will replace the stored values. 
 1821: #        
 1822: # Output:
 1823: #  
 1824: # javascript function - set_form_elements() which sets form elements,
 1825: # expects an argument: formname - the name of the form according to 
 1826: # the DOM, e.g., document.compose
 1827: 
 1828: sub set_form_elements {
 1829:     my ($elements,$stored) = @_;
 1830:     my %values;
 1831:     my $output .= 'function setFormElements(courseForm) {
 1832: ';
 1833:     if (defined($stored)) {
 1834:         foreach my $name (keys(%{$stored})) {
 1835:             if (exists($$elements{$name})) {
 1836:                 if (ref($$stored{$name}) eq 'ARRAY') {
 1837:                     $values{$name} = $$stored{$name};
 1838:                 } else {
 1839:                     @{$values{$name}} = ($$stored{$name});
 1840:                 }
 1841:             }
 1842:         }
 1843:     }
 1844: 
 1845:     foreach my $key (keys(%env)) {
 1846:         if ($key =~ /^form\.(.+)$/) {
 1847:             my $name = $1;
 1848:             if (exists($$elements{$name})) {
 1849:                 @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
 1850:             }
 1851:         }
 1852:     }
 1853: 
 1854:     foreach my $name (keys(%values)) {
 1855:         for (my $i=0; $i<@{$values{$name}}; $i++) {
 1856:             $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
 1857:             $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
 1858:             $values{$name}[$i] =~ s/"/\\"/g;
 1859:         }
 1860:         if ($$elements{$name} eq 'text') {
 1861:             my $numvalues = @{$values{$name}};
 1862:             if ($numvalues > 1) {
 1863:                 my $valuestring = join('","',@{$values{$name}});
 1864:                 $output .= qq|
 1865:   var textvalues = new Array ("$valuestring");
 1866:   var total = courseForm.elements['$name'].length;
 1867:   if (total > $numvalues) {
 1868:       total = $numvalues;
 1869:   }    
 1870:   for (var i=0; i<total; i++) {
 1871:       courseForm.elements['$name']\[i].value = textvalues[i];
 1872:   }
 1873: |;
 1874:             } else {
 1875:                 $output .= qq|
 1876:   courseForm.elements['$name'].value = "$values{$name}[0]";
 1877: |;
 1878:             }
 1879:         } else {
 1880:             $output .=  qq|
 1881:   var elementLength = courseForm.elements['$name'].length;
 1882:   if (elementLength==undefined) {
 1883: |;
 1884:             foreach my $value (@{$values{$name}}) {
 1885:                 if ($$elements{$name} eq 'selectbox') {
 1886:                     $output .=  qq|
 1887:       if (courseForm.elements['$name'].options[0].value == "$value") {
 1888:           courseForm.elements['$name'].options[0].selected = true;
 1889:       }|;
 1890:                 } elsif (($$elements{$name} eq 'radio') ||
 1891:                          ($$elements{$name} eq 'checkbox')) {
 1892:                     $output .= qq|
 1893:       if (courseForm.elements['$name'].value == "$value") {
 1894:           courseForm.elements['$name'].checked = true;
 1895:       }|;
 1896:                 }
 1897:             }
 1898:             $output .= qq|
 1899:   }
 1900:   else {
 1901:       for (var i=0; i<courseForm.elements['$name'].length; i++) {
 1902: |;
 1903:             if ($$elements{$name} eq 'selectbox') {
 1904:                 $output .=  qq|
 1905:           courseForm.elements['$name'].options[i].selected = false;|;
 1906:             } elsif (($$elements{$name} eq 'radio') || 
 1907:                      ($$elements{$name} eq 'checkbox')) {
 1908:                 $output .= qq|
 1909:           courseForm.elements['$name']\[i].checked = false;|; 
 1910:             }
 1911:             $output .= qq|
 1912:       }
 1913:       for (var j=0; j<courseForm.elements['$name'].length; j++) {
 1914: |;
 1915:             foreach my $value (@{$values{$name}}) {
 1916:                 if ($$elements{$name} eq 'selectbox') {
 1917:                     $output .=  qq|
 1918:           if (courseForm.elements['$name'].options[j].value == "$value") {
 1919:               courseForm.elements['$name'].options[j].selected = true;
 1920:           }|;
 1921:                 } elsif (($$elements{$name} eq 'radio') ||
 1922:                          ($$elements{$name} eq 'checkbox')) { 
 1923:                       $output .= qq|
 1924:           if (courseForm.elements['$name']\[j].value == "$value") {
 1925:               courseForm.elements['$name']\[j].checked = true;
 1926:           }|;
 1927:                 }
 1928:             }
 1929:             $output .= qq|
 1930:       }
 1931:   }
 1932: |;
 1933:         }
 1934:     }
 1935:     $output .= "
 1936: }\n";
 1937:     return $output;
 1938: }
 1939: 
 1940: ##############################################
 1941: ##############################################
 1942: 
 1943: # javascript_valid_email
 1944: #
 1945: # Generates javascript to validate an e-mail address.
 1946: # Returns a javascript function which accetps a form field as argumnent, and
 1947: # returns false if field.value does not satisfy two regular expression matches
 1948: # for a valid e-mail address.  Backwards compatible with old browsers without
 1949: # support for javascript RegExp (just checks for @ in field.value in this case). 
 1950: 
 1951: sub javascript_valid_email {
 1952:     my $scripttag .= <<'END';
 1953: function validmail(field) {
 1954:     var str = field.value;
 1955:     if (window.RegExp) {
 1956:         var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
 1957:         var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
 1958:         var reg1 = new RegExp(reg1str);
 1959:         var reg2 = new RegExp(reg2str);
 1960:         if (!reg1.test(str) && reg2.test(str)) {
 1961:             return true;
 1962:         }
 1963:         return false;
 1964:     }
 1965:     else
 1966:     {
 1967:         if(str.indexOf("@") >= 0) {
 1968:             return true;
 1969:         }
 1970:         return false;
 1971:     }
 1972: }
 1973: END
 1974:     return $scripttag;
 1975: }
 1976: 
 1977: 
 1978: 
 1979: 1;
 1980: 
 1981: __END__

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