File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.209: download - view: text, annotated - select for diffs
Sat Apr 25 20:22:07 2009 UTC (15 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Recycle "success" style

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

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