File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.208: download - view: text, annotated - select for diffs
Sat Apr 25 16:53:13 2009 UTC (15 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Formatting the CSS code (make easier to read/debug)
Success message

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

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