File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.131: download - view: text, annotated - select for diffs
Thu Jun 1 19:30:49 2006 UTC (17 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
-xhtmlize

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

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