File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.133: download - view: text, annotated - select for diffs
Wed Jun 14 18:34:46 2006 UTC (17 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- from mlucas some of BUG#3763

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

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