File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.101: download - view: text, annotated - select for diffs
Tue Nov 30 18:42:09 2004 UTC (19 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
If trailing / was removed, add it back.  Fix error caused when selecting /priv/$username (result of 1.94 change).

    1: # The LearningOnline Network with CAPA
    2: # a pile of common html routines
    3: #
    4: # $Id: lonhtmlcommon.pm,v 1.101 2004/11/30 18:42:09 raeburn 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 Time::Local;
   59: use Time::HiRes;
   60: use Apache::lonlocal;
   61: use strict;
   62: 
   63: ##############################################
   64: ##############################################
   65: 
   66: =pod
   67: 
   68: =item authorbombs
   69: 
   70: =cut
   71: 
   72: ##############################################
   73: ##############################################
   74: 
   75: sub authorbombs {
   76:     my $url=shift;
   77:     $url=&Apache::lonnet::declutter($url);
   78:     my ($udom,$uname)=($url=~/^(\w+)\/(\w+)\//);
   79:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
   80:     foreach (keys %bombs) {
   81: 	if ($_=~/^$udom\/$uname\//) {
   82: 	    return '<a href="/adm/bombs/'.$url.
   83: 		'"><img src="/adm/lonMisc/bomb.gif" border="0" /></a>'.
   84: 		&Apache::loncommon::help_open_topic('About_Bombs');
   85: 	}
   86:     }
   87:     return '';
   88: }
   89: 
   90: ##############################################
   91: ##############################################
   92: 
   93: sub recent_filename {
   94:     my $area=shift;
   95:     return 'nohist_recent_'.&Apache::lonnet::escape($area);
   96: }
   97: 
   98: sub store_recent {
   99:     my ($area,$name,$value)=@_;
  100:     my $file=&recent_filename($area);
  101:     my %recent=&Apache::lonnet::dump($file);
  102:     if (scalar(keys(%recent))>10) {
  103: # remove oldest value
  104: 	my $oldest=time;
  105: 	my $delkey='';
  106: 	foreach (keys %recent) {
  107: 	    my $thistime=(split(/\&/,$recent{$_}))[0];
  108: 	    if ($thistime<$oldest) {
  109: 		$oldest=$thistime;
  110: 		$delkey=$_;
  111: 	    }
  112: 	}
  113: 	&Apache::lonnet::del($file,[$delkey]);
  114:     }
  115: # store new value
  116:     &Apache::lonnet::put($file,{ $name => 
  117: 				 time.'&'.&Apache::lonnet::escape($value) });
  118: }
  119: 
  120: sub remove_recent {
  121:     my ($area,$names)=@_;
  122:     my $file=&recent_filename($area);
  123:     return &Apache::lonnet::del($file,$names);
  124: }
  125: 
  126: sub select_recent {
  127:     my ($area,$fieldname,$event)=@_;
  128:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  129:     my $return="\n<select name='$fieldname'".
  130: 	($event?" onchange='$event'":'').
  131: 	">\n<option value=''>--- ".&mt('Recent')." ---</option>";
  132:     foreach (sort keys %recent) {
  133: 	unless ($_=~/^error\:/) {
  134: 	    my $escaped = &Apache::loncommon::escape_url($_);
  135:             if ($_ =~ /\/$/ && $escaped !~ /\/$/) {
  136:                 $escaped .= '/';
  137:             }
  138: 	    $return.="\n<option value='$escaped'>".
  139: 		&Apache::lonnet::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:                   &Apache::lonnet::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:     my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
  184:         'value="'.$value.'" '.$special.' />';
  185:     return $Str;
  186: }
  187: 
  188: ##############################################
  189: ##############################################
  190: 
  191: =pod
  192: 
  193: =item checkbox
  194: 
  195: =cut
  196: 
  197: ##############################################
  198: ##############################################
  199: sub checkbox {
  200:     my ($name,$checked,$value) = @_;
  201:     my $Str = '<input type="checkbox" name="'.$name.'" ';
  202:     if (defined($value)) {
  203:         $Str .= 'value="'.$value.'"';
  204:     } 
  205:     if ($checked) {
  206:         $Str .= ' checked="1"';
  207:     }
  208:     $Str .= ' />';
  209:     return $Str;
  210: }
  211: 
  212: ##############################################
  213: ##############################################
  214: 
  215: =pod
  216: 
  217: =item &date_setter
  218: 
  219: &date_setter returns html and javascript for a compact date-setting form.
  220: To retrieve values from it, use &get_date_from_form().
  221: 
  222: Inputs
  223: 
  224: =over 4
  225: 
  226: =item $dname 
  227: 
  228: The name to prepend to the form elements.  
  229: The form elements defined will be dname_year, dname_month, dname_day,
  230: dname_hour, dname_min, and dname_sec.
  231: 
  232: =item $currentvalue
  233: 
  234: The current setting for this time parameter.  A unix format time
  235: (time in seconds since the beginning of Jan 1st, 1970, GMT.  
  236: An undefined value is taken to indicate the value is the current time.
  237: Also, to be explicit, a value of 'now' also indicates the current time.
  238: 
  239: =item $special
  240: 
  241: Additional html/javascript to be associated with each element in
  242: the date_setter.  See lonparmset for example usage.
  243: 
  244: =item $includeempty 
  245: 
  246: =item $state
  247: 
  248: Specifies the initial state of the form elements.  Either 'disabled' or empty.
  249: Defaults to empty, which indiciates the form elements are not disabled. 
  250: 
  251: =back
  252: 
  253: Bugs
  254: 
  255: The method used to restrict user input will fail in the year 2400.
  256: 
  257: =cut
  258: 
  259: ##############################################
  260: ##############################################
  261: sub date_setter {
  262:     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
  263:         $no_hh_mm_ss) = @_;
  264:     if (! defined($state) || $state ne 'disabled') {
  265:         $state = '';
  266:     }
  267:     if (! defined($no_hh_mm_ss)) {
  268:         $no_hh_mm_ss = 0;
  269:     }
  270:     if (! defined($currentvalue) || $currentvalue eq 'now') {
  271: 	unless ($includeempty) {
  272: 	    $currentvalue = time;
  273: 	} else {
  274: 	    $currentvalue = 0;
  275: 	}
  276:     }
  277:     # other potentially useful values:     wkday,yrday,is_daylight_savings
  278:     my ($sec,$min,$hour,$mday,$month,$year)=('','',undef,'','','');
  279:     if ($currentvalue) {
  280: 	($sec,$min,$hour,$mday,$month,$year,undef,undef,undef) = 
  281: 	    localtime($currentvalue);
  282: 	$year += 1900;
  283:     }
  284:     my $result = "\n<!-- $dname date setting form -->\n";
  285:     $result .= <<ENDJS;
  286: <script language="Javascript">
  287:     function $dname\_checkday() {
  288:         var day   = document.$formname.$dname\_day.value;
  289:         var month = document.$formname.$dname\_month.value;
  290:         var year  = document.$formname.$dname\_year.value;
  291:         var valid = true;
  292:         if (day < 1) {
  293:             document.$formname.$dname\_day.value = 1;
  294:         } 
  295:         if (day > 31) {
  296:             document.$formname.$dname\_day.value = 31;
  297:         }
  298:         if ((month == 1)  || (month == 3)  || (month == 5)  ||
  299:             (month == 7)  || (month == 8)  || (month == 10) ||
  300:             (month == 12)) {
  301:             if (day > 31) {
  302:                 document.$formname.$dname\_day.value = 31;
  303:                 day = 31;
  304:             }
  305:         } else if (month == 2 ) {
  306:             if ((year % 4 == 0) && (year % 100 != 0)) {
  307:                 if (day > 29) {
  308:                     document.$formname.$dname\_day.value = 29;
  309:                 }
  310:             } else if (day > 29) {
  311:                 document.$formname.$dname\_day.value = 28;
  312:             }
  313:         } else if (day > 30) {
  314:             document.$formname.$dname\_day.value = 30;
  315:         }
  316:     }
  317:     
  318:     function $dname\_disable() {
  319:         document.$formname.$dname\_month.disabled=true;
  320:         document.$formname.$dname\_day.disabled=true;
  321:         document.$formname.$dname\_year.disabled=true;
  322:         document.$formname.$dname\_hour.disabled=true;
  323:         document.$formname.$dname\_minute.disabled=true;
  324:         document.$formname.$dname\_second.disabled=true;
  325:     }
  326: 
  327:     function $dname\_enable() {
  328:         document.$formname.$dname\_month.disabled=false;
  329:         document.$formname.$dname\_day.disabled=false;
  330:         document.$formname.$dname\_year.disabled=false;
  331:         document.$formname.$dname\_hour.disabled=false;
  332:         document.$formname.$dname\_minute.disabled=false;
  333:         document.$formname.$dname\_second.disabled=false;        
  334:     }
  335: 
  336:     function $dname\_opencalendar() {
  337:         if (! document.$formname.$dname\_month.disabled) {
  338:             var calwin=window.open(
  339: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
  340: document.$formname.$dname\_month.value+"&year="+
  341: document.$formname.$dname\_year.value,
  342:              "LONCAPAcal",
  343:               "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
  344:         }
  345: 
  346:     }
  347: </script>
  348: ENDJS
  349:     $result .= '  <nobr>';
  350:     my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
  351:     # Month
  352:     my @Months = qw/January February  March     April   May      June 
  353:                     July    August    September October November December/;
  354:     # Pad @Months with a bogus value to make indexing easier
  355:     unshift(@Months,'If you can read this an error occurred');
  356:     if ($includeempty) { $monthselector.="<option value=''></option>"; }
  357:     for(my $m = 1;$m <=$#Months;$m++) {
  358:         $monthselector .= qq{      <option value="$m" };
  359:         $monthselector .= "selected " if ($m-1 eq $month);
  360:         $monthselector .= '> '.&mt($Months[$m]).' </option>';
  361:     }
  362:     $monthselector.= '  </select>';
  363:     # Day
  364:     my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
  365:     # Year
  366:     my $yearselector = qq{<input type="year" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
  367:     #
  368:     my $hourselector = qq{<select name="$dname\_hour" $special $state >};
  369:     if ($includeempty) { 
  370:         $hourselector.=qq{<option value=''></option>};
  371:     }
  372:     for (my $h = 0;$h<24;$h++) {
  373:         $hourselector .= qq{<option value="$h" };
  374:         $hourselector .= "selected " if (defined($hour) && $hour == $h);
  375:         $hourselector .= ">";
  376:         my $timest='';
  377:         if ($h == 0) {
  378:             $timest .= "12 am";
  379:         } elsif($h == 12) {
  380:             $timest .= "12 noon";
  381:         } elsif($h < 12) {
  382:             $timest .= "$h am";
  383:         } else {
  384:             $timest .= $h-12 ." pm";
  385:         }
  386:         $timest=&mt($timest);
  387:         $hourselector .= $timest." </option>\n";
  388:     }
  389:     $hourselector .= "  </select>\n";
  390:     my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
  391:     my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
  392:     my $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
  393:     #
  394:     if ($no_hh_mm_ss) {
  395:         $result .= &mt('[_1] [_2] [_3] [_4]Select Date[_5]',
  396:                        $monthselector,$dayselector,$yearselector,
  397:                        $cal_link,'</a>');
  398:     } else {
  399:         $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s [_7]Select Date[_8]',
  400:                        $monthselector,$dayselector,$yearselector,
  401:                        $hourselector,$minuteselector,$secondselector,
  402:                        $cal_link,'</a>');
  403:     }
  404:     $result .= "</nobr>\n<!-- end $dname date setting form -->\n";
  405:     return $result;
  406: }
  407: 
  408: ##############################################
  409: ##############################################
  410: 
  411: =pod
  412: 
  413: =item &get_date_from_form
  414: 
  415: get_date_from_form retrieves the date specified in an &date_setter form.
  416: 
  417: Inputs:
  418: 
  419: =over 4
  420: 
  421: =item $dname
  422: 
  423: The name passed to &datesetter, which prefixes the form elements.
  424: 
  425: =item $defaulttime
  426: 
  427: The unix time to use as the default in case of poor inputs.
  428: 
  429: =back
  430: 
  431: Returns: Unix time represented in the form.
  432: 
  433: =cut
  434: 
  435: ##############################################
  436: ##############################################
  437: sub get_date_from_form {
  438:     my ($dname) = @_;
  439:     my ($sec,$min,$hour,$day,$month,$year);
  440:     #
  441:     if (defined($ENV{'form.'.$dname.'_second'})) {
  442:         my $tmpsec = $ENV{'form.'.$dname.'_second'};
  443:         if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
  444:             $sec = $tmpsec;
  445:         }
  446: 	if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
  447:     } else {
  448:         $sec = 0;
  449:     }
  450:     if (defined($ENV{'form.'.$dname.'_minute'})) {
  451:         my $tmpmin = $ENV{'form.'.$dname.'_minute'};
  452:         if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
  453:             $min = $tmpmin;
  454:         }
  455: 	if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
  456:     } else {
  457:         $min = 0;
  458:     }
  459:     if (defined($ENV{'form.'.$dname.'_hour'})) {
  460:         my $tmphour = $ENV{'form.'.$dname.'_hour'};
  461:         if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
  462:             $hour = $tmphour;
  463:         }
  464:     } else {
  465:         $hour = 0;
  466:     }
  467:     if (defined($ENV{'form.'.$dname.'_day'})) {
  468:         my $tmpday = $ENV{'form.'.$dname.'_day'};
  469:         if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
  470:             $day = $tmpday;
  471:         }
  472:     }
  473:     if (defined($ENV{'form.'.$dname.'_month'})) {
  474:         my $tmpmonth = $ENV{'form.'.$dname.'_month'};
  475:         if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
  476:             $month = $tmpmonth - 1;
  477:         }
  478:     }
  479:     if (defined($ENV{'form.'.$dname.'_year'})) {
  480:         my $tmpyear = $ENV{'form.'.$dname.'_year'};
  481:         if (($tmpyear =~ /^\d+$/) && ($tmpyear > 1900)) {
  482:             $year = $tmpyear - 1900;
  483:         }
  484:     }
  485:     if (($year<70) || ($year>137)) { return undef; }
  486:     if (defined($sec) && defined($min)   && defined($hour) &&
  487:         defined($day) && defined($month) && defined($year) &&
  488:         eval(&timelocal($sec,$min,$hour,$day,$month,$year))) {
  489:         return &timelocal($sec,$min,$hour,$day,$month,$year);
  490:     } else {
  491:         return undef;
  492:     }
  493: }
  494: 
  495: ##############################################
  496: ##############################################
  497: 
  498: =pod
  499: 
  500: =item &pjump_javascript_definition()
  501: 
  502: Returns javascript defining the 'pjump' function, which opens up a
  503: parameter setting wizard.
  504: 
  505: =cut
  506: 
  507: ##############################################
  508: ##############################################
  509: sub pjump_javascript_definition {
  510:     my $Str = <<END;
  511:     function pjump(type,dis,value,marker,ret,call) {
  512:         parmwin=window.open("/adm/rat/parameter.html?type="+escape(type)
  513:                  +"&value="+escape(value)+"&marker="+escape(marker)
  514:                  +"&return="+escape(ret)
  515:                  +"&call="+escape(call)+"&name="+escape(dis),"LONCAPAparms",
  516:                  "height=350,width=350,scrollbars=no,menubar=no");
  517:     }
  518: END
  519:     return $Str;
  520: }
  521: 
  522: ##############################################
  523: ##############################################
  524: 
  525: =pod
  526: 
  527: =item &javascript_nothing()
  528: 
  529: Return an appropriate null for the users browser.  This is used
  530: as the first arguement for window.open calls when you want a blank
  531: window that you can then write to.
  532: 
  533: =cut
  534: 
  535: ##############################################
  536: ##############################################
  537: sub javascript_nothing {
  538:     # mozilla and other browsers work with "''", but IE on mac does not.
  539:     my $nothing = "''";
  540:     my $user_browser;
  541:     my $user_os;
  542:     $user_browser = $ENV{'browser.type'} if (exists($ENV{'browser.type'}));
  543:     $user_os      = $ENV{'browser.os'}   if (exists($ENV{'browser.os'}));
  544:     if (! defined($user_browser) || ! defined($user_os)) {
  545:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  546:                            &Apache::loncommon::decode_user_agent();
  547:     }
  548:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
  549:         $nothing = "'javascript:void(0);'";
  550:     }
  551:     return $nothing;
  552: }
  553: 
  554: ##############################################
  555: ##############################################
  556: sub javascript_docopen {
  557:     # safari does not understand document.open() and loads "text/html"
  558:     my $nothing = "''";
  559:     my $user_browser;
  560:     my $user_os;
  561:     $user_browser = $ENV{'browser.type'} if (exists($ENV{'browser.type'}));
  562:     $user_os      = $ENV{'browser.os'}   if (exists($ENV{'browser.os'}));
  563:     if (! defined($user_browser) || ! defined($user_os)) {
  564:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  565:                            &Apache::loncommon::decode_user_agent();
  566:     }
  567:     if ($user_browser eq 'safari' && $user_os =~ 'mac') {
  568:         $nothing = "document.clear()";
  569:     } else {
  570: 	$nothing = "document.open('text/html','replace')";
  571:     }
  572:     return $nothing;
  573: }
  574: 
  575: 
  576: ##############################################
  577: ##############################################
  578: 
  579: =pod
  580: 
  581: =item &StatusOptions()
  582: 
  583: Returns html for a selection box which allows the user to choose the
  584: enrollment status of students.  The selection box name is 'Status'.
  585: 
  586: Inputs:
  587: 
  588: $status: the currently selected status.  If undefined the value of
  589: $ENV{'form.Status'} is taken.  If that is undefined, a value of 'Active'
  590: is used.
  591: 
  592: $formname: The name of the form.  If defined the onchange attribute of
  593: the selection box is set to document.$formname.submit().
  594: 
  595: $size: the size (number of lines) of the selection box.
  596: 
  597: $onchange: javascript to use when the value is changed.  Enclosed in 
  598: double quotes, ""s, not single quotes.
  599: 
  600: Returns: a perl string as described.
  601: 
  602: =cut
  603: 
  604: ##############################################
  605: ##############################################
  606: sub StatusOptions {
  607:     my ($status, $formName,$size,$onchange)=@_;
  608:     $size = 1 if (!defined($size));
  609:     if (! defined($status)) {
  610:         $status = 'Active';
  611:         $status = $ENV{'form.Status'} if (exists($ENV{'form.Status'}));
  612:     }
  613: 
  614:     my $OpSel1 = '';
  615:     my $OpSel2 = '';
  616:     my $OpSel3 = '';
  617: 
  618:     if($status eq 'Any')         { $OpSel3 = ' selected'; }
  619:     elsif($status eq 'Expired' ) { $OpSel2 = ' selected'; }
  620:     else                         { $OpSel1 = ' selected'; }
  621: 
  622:     my $Str = '';
  623:     $Str .= '<select name="Status"';
  624:     if(defined($formName) && $formName ne '' && ! defined($onchange)) {
  625:         $Str .= ' onchange="document.'.$formName.'.submit()"';
  626:     }
  627:     if (defined($onchange)) {
  628:         $Str .= ' onchange="'.$onchange.'"';
  629:     }
  630:     $Str .= ' size="'.$size.'" ';
  631:     $Str .= '>'."\n";
  632:     $Str .= '<option value="Active" '.$OpSel1.'>'.
  633:         &mt('Currently Enrolled').'</option>'."\n";
  634:     $Str .= '<option value="Expired" '.$OpSel2.'>'.
  635:         &mt('Previously Enrolled').'</option>'."\n";
  636:     $Str .= '<option value="Any" '.$OpSel3.'>'.
  637:         &mt('Any Enrollment Status').'</option>'."\n";
  638:     $Str .= '</select>'."\n";
  639: }
  640: 
  641: ########################################################
  642: ########################################################
  643: 
  644: =pod
  645: 
  646: =item Progess Window Handling Routines
  647: 
  648: These routines handle the creation, update, increment, and closure of 
  649: progress windows.  The progress window reports to the user the number
  650: of items completed and an estimate of the time required to complete the rest.
  651: 
  652: =over 4
  653: 
  654: 
  655: =item &Create_PrgWin
  656: 
  657: Writes javascript to the client to open a progress window and returns a
  658: data structure used for bookkeeping.
  659: 
  660: Inputs
  661: 
  662: =over 4
  663: 
  664: =item $r Apache request
  665: 
  666: =item $title The title of the progress window
  667: 
  668: =item $heading A description (usually 1 line) of the process being initiated.
  669: 
  670: =item $number_to_do The total number of items being processed.
  671: 
  672: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
  673:        specified)
  674: 
  675: =item $width Specify the width in charaters of the input field.
  676: 
  677: =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
  678: 
  679: =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 
  680: 
  681: =back
  682: 
  683: Returns a hash containing the progress state data structure.
  684: 
  685: 
  686: =item &Update_PrgWin
  687: 
  688: Updates the text in the progress indicator.  Does not increment the count.
  689: See &Increment_PrgWin.
  690: 
  691: Inputs:
  692: 
  693: =over 4
  694: 
  695: =item $r Apache request
  696: 
  697: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
  698: 
  699: =item $displaystring The string to write to the status indicator
  700: 
  701: =back
  702: 
  703: Returns: none
  704: 
  705: 
  706: =item Increment_PrgWin
  707: 
  708: Increment the count of items completed for the progress window by 1.  
  709: 
  710: Inputs:
  711: 
  712: =over 4
  713: 
  714: =item $r Apache request
  715: 
  716: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  717: 
  718: =item $extraInfo A description of the items being iterated over.  Typically
  719: 'student'.
  720: 
  721: =back
  722: 
  723: Returns: none
  724: 
  725: 
  726: =item Close_PrgWin
  727: 
  728: Closes the progress window.
  729: 
  730: Inputs:
  731: 
  732: =over 4 
  733: 
  734: =item $r Apache request
  735: 
  736: =item $prog_state Pointer to the data structure returned by Create_PrgWin
  737: 
  738: =back
  739: 
  740: Returns: none
  741: 
  742: =back
  743: 
  744: =cut
  745: 
  746: ########################################################
  747: ########################################################
  748: 
  749: my $uniq=0;
  750: sub get_uniq_name {
  751:     $uniq++;
  752:     return 'uniquename'.$uniq;
  753: }
  754: 
  755: # Create progress
  756: sub Create_PrgWin {
  757:     my ($r, $title, $heading, $number_to_do,$type,$width,$formname,
  758: 	$inputname)=@_;
  759:     if (!defined($type)) { $type='popup'; }
  760:     if (!defined($width)) { $width=55; }
  761:     my %prog_state;
  762:     $prog_state{'type'}=$type;
  763:     if ($type eq 'popup') {
  764: 	$prog_state{'window'}='popwin';
  765: 	#the whole function called through timeout is due to issues
  766: 	#in mozilla Read BUG #2665 if you want to know the whole story
  767: 	&r_print($r,'<script>'.
  768:         "var popwin;
  769:          function openpopwin () {
  770:          popwin=open(\'\',\'popwin\',\'width=400,height=100\');".
  771:         "popwin.document.writeln(\'<html><head><title>$title</title></head>".
  772: 	      "<body bgcolor=\"#88DDFF\">".
  773:               "<h4>$heading</h4>".
  774:               "<form name=popremain>".
  775:               '<input type="text" size="'.$width.'" name="remaining" value="'.
  776: 	      &mt('Starting').'"></form>'.
  777:               "</body></html>\');".
  778:         "popwin.document.close();}".
  779:         "\nwindow.setTimeout(openpopwin,0)</script>");
  780: 	$prog_state{'formname'}='popremain';
  781: 	$prog_state{'inputname'}="remaining";
  782:     } elsif ($type eq 'inline') {
  783: 	$prog_state{'window'}='window';
  784: 	if (!$formname) {
  785: 	    $prog_state{'formname'}=&get_uniq_name();
  786: 	    &r_print($r,'<form name="'.$prog_state{'formname'}.'">');
  787: 	} else {
  788: 	    $prog_state{'formname'}=$formname;
  789: 	}
  790: 	if (!$inputname) {
  791: 	    $prog_state{'inputname'}=&get_uniq_name();
  792: 	    &r_print($r,$heading.' <input type="text" name="'.$prog_state{'inputname'}.
  793: 		     '" size="'.$width.'" />');
  794: 	} else {
  795: 	    $prog_state{'inputname'}=$inputname;
  796: 	    
  797: 	}
  798: 	if (!$formname) { &r_print($r,'</form>'); }
  799: 	&Update_PrgWin($r,\%prog_state,&mt('Starting'));
  800:     }
  801: 
  802:     $prog_state{'done'}=0;
  803:     $prog_state{'firststart'}=&Time::HiRes::time();
  804:     $prog_state{'laststart'}=&Time::HiRes::time();
  805:     $prog_state{'max'}=$number_to_do;
  806:     
  807:     return %prog_state;
  808: }
  809: 
  810: # update progress
  811: sub Update_PrgWin {
  812:     my ($r,$prog_state,$displayString)=@_;
  813:     &r_print($r,'<script>'.$$prog_state{'window'}.'.document.'.
  814: 	     $$prog_state{'formname'}.'.'.
  815: 	     $$prog_state{'inputname'}.'.value="'.
  816: 	     $displayString.'";</script>');
  817:     $$prog_state{'laststart'}=&Time::HiRes::time();
  818: }
  819: 
  820: # increment progress state
  821: sub Increment_PrgWin {
  822:     my ($r,$prog_state,$extraInfo)=@_;
  823:     $$prog_state{'done'}++;
  824:     my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
  825:         $$prog_state{'done'} *
  826: 	($$prog_state{'max'}-$$prog_state{'done'});
  827:     $time_est = int($time_est);
  828:     #
  829:     my $min = int($time_est/60);
  830:     my $sec = $time_est % 60;
  831:     # 
  832:     my $str;
  833:     if ($min == 0 && $sec > 1) {
  834:         $str = '[_2] seconds';
  835:     } elsif ($min == 1 && $sec > 1) {
  836:         $str = '1 minute [_2] seconds';
  837:     } elsif ($min == 1 && $sec < 2) {
  838:         $str = '1 minute';
  839:     } elsif ($min < 10 && $sec > 1) {
  840:         $str = '[_1] minutes, [_2] seconds';
  841:     } elsif ($min >= 10 || $sec < 2) {
  842:         $str = '[_1] minutes';
  843:     }
  844:     $time_est = &mt($str,$min,$sec);
  845:     #
  846:     my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
  847:     if ($lasttime > 9) {
  848:         $lasttime = int($lasttime);
  849:     } elsif ($lasttime < 0.01) {
  850:         $lasttime = 0;
  851:     } else {
  852:         $lasttime = sprintf("%3.2f",$lasttime);
  853:     }
  854:     if ($lasttime == 1) {
  855:         $lasttime = '('.$lasttime.' '.&mt('second for').' '.$extraInfo.')';
  856:     } else {
  857:         $lasttime = '('.$lasttime.' '.&mt('seconds for').' '.$extraInfo.')';
  858:     }
  859:     #
  860:     my $user_browser = $ENV{'browser.type'} if (exists($ENV{'browser.type'}));
  861:     my $user_os      = $ENV{'browser.os'}   if (exists($ENV{'browser.os'}));
  862:     if (! defined($user_browser) || ! defined($user_os)) {
  863:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  864:                            &Apache::loncommon::decode_user_agent();
  865:     }
  866:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
  867:         $lasttime = '';
  868:     }
  869:     &r_print($r,'<script>'.$$prog_state{'window'}.'.document.'.
  870: 	     $$prog_state{'formname'}.'.'.
  871: 	     $$prog_state{'inputname'}.'.value="'.
  872: 	     $$prog_state{'done'}.'/'.$$prog_state{'max'}.
  873: 	     ': '.$time_est.' '.&mt('remaining').' '.$lasttime.'";'.'</script>');
  874:     $$prog_state{'laststart'}=&Time::HiRes::time();
  875: }
  876: 
  877: # close Progress Line
  878: sub Close_PrgWin {
  879:     my ($r,$prog_state)=@_;
  880:     if ($$prog_state{'type'} eq 'popup') {
  881: 	&r_print($r,'<script>popwin.close()</script>'."\n");
  882:     } elsif ($$prog_state{'type'} eq 'inline') {
  883: 	&Update_PrgWin($r,$prog_state,&mt('Done'));
  884:     }
  885:     undef(%$prog_state);
  886: }
  887: 
  888: sub r_print {
  889:     my ($r,$to_print)=@_;
  890:     if ($r) {
  891: 	$r->print($to_print);
  892: 	$r->rflush();
  893:     } else {
  894: 	print($to_print);
  895:     }
  896: }
  897: 
  898: # ------------------------------------------------------- Puts directory header
  899: 
  900: sub crumbs {
  901:     my ($uri,$target,$prefix,$form,$size,$noformat)=@_;
  902:     if (! defined($size)) {
  903:         $size = '+2';
  904:     }
  905:     if ($target) {
  906:         $target = ' target="'.
  907:                   &Apache::loncommon::escape_single($target).'"';
  908:     }
  909:     my $output='';
  910:     unless ($noformat) { $output.='<br /><tt><b>'; }
  911:     $output.='<font size="'.$size.'">'.$prefix.'/';
  912:     if ($ENV{'user.adv'}) {
  913: 	my $path=$prefix.'/';
  914: 	foreach my $dir (split('/',$uri)) {
  915:             if (! $dir) { next; }
  916:             $path .= $dir;
  917: 	    unless ($path eq $uri) { $path.='/'; }
  918:             my $linkpath = &Apache::loncommon::escape_single($path);
  919:             if ($form) {
  920: 		$linkpath=
  921:                     qq{javascript:$form.action='$linkpath';$form.submit();};
  922:             }
  923: 	    $output.=qq{<a href="$linkpath" $target>$dir</a>/};
  924: 	}
  925:     } else {
  926: 	$output.=$uri;
  927:     }
  928:     unless ($uri=~/\/$/) { $output=~s/\/$//; }
  929:     return $output.'</font>'.($noformat?'':'</b></tt><br />');
  930: }
  931: 
  932: # --------------------- A function that generates a window for the spellchecker
  933: 
  934: sub spellheader {
  935:     my $nothing = &javascript_nothing();
  936:     return (<<ENDCHECK);
  937: <script type="text/javascript"> 
  938: //<!-- BEGIN LON-CAPA Internal
  939: var checkwin;
  940: 
  941: function spellcheckerwindow() {
  942:     checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
  943:     checkwin.document.writeln('<html><body bgcolor="#DDDDDD"><form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="" /></form></body></html>');
  944:     checkwin.document.close();
  945: }
  946: // END LON-CAPA Internal -->
  947: </script>
  948: ENDCHECK
  949: }
  950: 
  951: # ---------------------------------- Generate link to spell checker for a field
  952: 
  953: sub spelllink {
  954:     my ($form,$field)=@_;
  955:     my $linktext=&mt('Check Spelling');
  956:     return (<<ENDLINK);
  957: <a href="javascript:if (typeof(document.$form.onsubmit)!='undefined') { document.$form.onsubmit();};spellcheckerwindow();checkwin.document.forms.spellcheckform.text.value=this.document.forms.$form.$field.value;checkwin.document.forms.spellcheckform.submit();">$linktext</a>
  958: ENDLINK
  959: }
  960: 
  961: # ------------------------------------------------- Output headers for HTMLArea
  962: 
  963: sub htmlareaheaders {
  964:     if (&htmlareablocked()) { return ''; }
  965:     unless (&htmlareabrowser()) { return ''; }
  966:     my $lang='en';
  967:     if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
  968: 	$lang=&mt('htmlarea_lang');
  969:     }
  970:     return (<<ENDHEADERS);
  971: <script type="text/javascript">
  972: _editor_url='/htmlarea/';
  973: _editor_lang='$lang';
  974: </script>
  975: <script type="text/javascript" src="/htmlarea/htmlarea.js"></script>
  976: ENDHEADERS
  977: }
  978: 
  979: # ------------------------------------------------- Activate additional buttons
  980: 
  981: sub htmlareaaddbuttons {
  982:     if (&htmlareablocked()) { return ''; }
  983:     unless (&htmlareabrowser()) { return ''; }
  984:     return (<<ENDADDBUTTON);
  985:     var config=new HTMLArea.Config();
  986:     config.registerButton('ed_math','LaTeX Inline',
  987: 			  '/htmlarea/images/ed_math.gif',false,
  988: 			    function(editor,id) {
  989: 			      editor.surroundHTML('&nbsp;<m>\$','\$</m>&nbsp;');
  990: 			    }
  991: 			  );
  992:     config.registerButton('ed_math_eqn','LaTeX Equation',
  993: 			  '/htmlarea/images/ed_math_eqn.gif',false,
  994: 			    function(editor,id) {
  995: 			      editor.surroundHTML(
  996: 				     '&nbsp;\\n<center><m>\\\\[','\\\\]</m></center>\\n&nbsp;');
  997: 			    }
  998: 			  );
  999:     config.toolbar.push(['ed_math','ed_math_eqn']);
 1000: ENDADDBUTTON
 1001: }
 1002: 
 1003: # ----------------------------------------------------------------- Preferences
 1004: 
 1005: sub disablelink {
 1006:     my @fields=@_;
 1007:     if (defined($#fields)) {
 1008: 	unless ($#fields>=0) { return ''; }
 1009:     }
 1010:     return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=off&returnurl=','<>&"').&Apache::lonnet::escape($ENV{'REQUEST_URI'}).'">'.&mt('Disable WYSIWYG Editor').'</a>';
 1011: }
 1012: 
 1013: sub enablelink {
 1014:     my @fields=@_;
 1015:     if (defined($#fields)) {
 1016: 	unless ($#fields>=0) { return ''; }
 1017:     }
 1018:     return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=on&returnurl=','<>&"').&Apache::lonnet::escape($ENV{'REQUEST_URI'}).'">'.&mt('Enable WYSIWYG Editor').'</a>';
 1019: }
 1020: 
 1021: # ----------------------------------------- Script to activate only some fields
 1022: 
 1023: sub htmlareaselectactive {
 1024:     my @fields=@_;
 1025:     unless (&htmlareabrowser()) { return ''; }
 1026:     if (&htmlareablocked()) { return '<br />'.&enablelink(@fields); }
 1027:     my $output='<script type="text/javascript" defer="1">'.
 1028: 	&htmlareaaddbuttons();
 1029:     foreach(@fields) {
 1030: 	$output.="\nHTMLArea.replace('$_',config);";
 1031:     }
 1032:     $output.="\nwindow.status='Activated Editfields';\n</script><br />".
 1033: 	&disablelink(@fields);
 1034:     return $output;
 1035: }
 1036: 
 1037: # --------------------------------------------------------------------- Blocked
 1038: 
 1039: sub htmlareablocked {
 1040:     unless ($ENV{'environment.wysiwygeditor'} eq 'on') { return 1; }
 1041:     return 0;
 1042: }
 1043: 
 1044: # ---------------------------------------- Browser capable of running HTMLArea?
 1045: 
 1046: sub htmlareabrowser {
 1047:     return 1;
 1048: }
 1049: 
 1050: ############################################################
 1051: ############################################################
 1052: 
 1053: =pod
 1054: 
 1055: =item breadcrumbs
 1056: 
 1057: Compiles the previously registered breadcrumbs into an series of links.
 1058: FAQ and BUG links will be placed on the left side of the table if they
 1059: are defined for the last registered breadcrumb.  
 1060: Additionally supports a 'component', which will be displayed on the
 1061: right side of the table (without a link).
 1062: A link to help for the component will be included if one is specified.
 1063: 
 1064: All inputs can be undef without problems.
 1065: 
 1066: Inputs: $color (the background color of the table returned),
 1067:         $component (the large text on the right side of the table),
 1068:         $component_help
 1069:         $function (role to get colors from)
 1070:         $domain   (domian of role)
 1071:         $menulink (boolean, controls whether to include a link to /adm/menu)
 1072: 
 1073: Returns a string containing breadcrumbs for the current page.
 1074: 
 1075: =item clear_breadcrumbs
 1076: 
 1077: Clears the previously stored breadcrumbs.
 1078: 
 1079: =item add_breadcrumb
 1080: 
 1081: Pushes a breadcrumb on the stack of crumbs.
 1082: 
 1083: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
 1084: are required.  If present the keys 'faq' and 'bug' will be used to provide
 1085: links to the FAQ and bug sites.
 1086: 
 1087: returns: nothing    
 1088: 
 1089: =cut
 1090: 
 1091: ############################################################
 1092: ############################################################
 1093: {
 1094:     my @Crumbs;
 1095:     
 1096:     sub breadcrumbs {
 1097:         my ($color,$component,$component_help,$function,$domain,$menulink,
 1098: 	    $helplink) = @_;
 1099:         if (! defined($color)) {
 1100:             if (! defined($function)) {
 1101:                 $function = &Apache::loncommon::get_users_function();
 1102:             }
 1103:             $color = &Apache::loncommon::designparm($function.'.tabbg',
 1104:                                                     $domain);
 1105:         }
 1106:         #
 1107:         my $Str = "\n".
 1108:             '<table width="100%" border="0" cellpadding="0" cellspacing="0">'.
 1109:             '<tr><td bgcolor="'.$color.'">'.
 1110:             '<font size="-1">';
 1111:         #
 1112:         # Make the faq and bug data cascade
 1113:         my $faq = '';
 1114:         my $bug = '';
 1115:         # The last breadcrumb does not have a link, so handle it separately.
 1116:         my $last = pop(@Crumbs);
 1117:         #
 1118:         # The first one should be the course or a menu link
 1119: 	if (!defined($menulink)) { $menulink=1; }
 1120:         if ($menulink) {
 1121:             my $description = 'Menu';
 1122:             if (exists($ENV{'request.course.id'}) && 
 1123:                 $ENV{'request.course.id'} ne '') {
 1124:                 $description = 
 1125:                     $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1126:             }
 1127:             unshift(@Crumbs,{
 1128:                     href   =>'/adm/menu',
 1129:                     title  =>'Go to main menu',
 1130:                     target =>'_top',
 1131:                     text   =>$description,
 1132:                 });
 1133:         }
 1134:         my $links .= 
 1135:             join('-&gt;',
 1136:                  map {
 1137:                      $faq = $_->{'faq'} if (exists($_->{'faq'}));
 1138:                      $bug = $_->{'bug'} if (exists($_->{'bug'}));
 1139:                      my $result = '<a href="'.$_->{'href'}.'" ';
 1140:                      if (defined($_->{'target'}) && $_->{'target'} ne '') {
 1141:                          $result .= 'target="'.$_->{'target'}.'" ';
 1142:                      }
 1143:                      $result .='title="'.&mt($_->{'title'}).'">'.
 1144:                          &mt($_->{'text'}).'</a>';
 1145:                      $result;
 1146:                      } @Crumbs
 1147:                  );
 1148:         $links .= '-&gt;' if ($links ne '');
 1149:         $links .= '<b>'.&mt($last->{'text'}).'</b>';
 1150:         #
 1151:         my $icons = '';
 1152:         $faq = $last->{'faq'} if (exists($last->{'faq'}));
 1153:         $bug = $last->{'bug'} if (exists($last->{'bug'}));
 1154: #        if ($faq ne '') {
 1155: #            $icons .= &Apache::loncommon::help_open_faq($faq);
 1156: #        }
 1157: #        if ($bug ne '') {
 1158: #            $icons .= &Apache::loncommon::help_open_bug($bug);
 1159: #        }
 1160: 	if ($helplink ne 'nohelp') {
 1161: 	    $icons .= &Apache::loncommon::help_open_menu($color,$component,$component_help,$function,$faq,$bug);
 1162: 	}
 1163:         if ($icons ne '') {
 1164:             $Str .= $icons.'&nbsp;';
 1165:         }
 1166:         #
 1167:         $Str .= $links.'</font></td>';
 1168:         #
 1169:         if (defined($component)) {
 1170:             $Str .= '<td align="right" bgcolor="'.$color.'">'.
 1171:                 '<font size="+1">'.&mt($component).'</font></td>';
 1172:         }
 1173:         $Str .= '</tr></table>'."\n";
 1174:         #
 1175:         # Return the @Crumbs stack to what we started with
 1176:         push(@Crumbs,$last);
 1177:         shift(@Crumbs);
 1178:         #
 1179:         return $Str;
 1180:     }
 1181: 
 1182:     sub clear_breadcrumbs {
 1183:         undef(@Crumbs);
 1184:     }
 1185: 
 1186:     sub add_breadcrumb {
 1187:         push (@Crumbs,@_);
 1188:     }
 1189: 
 1190: } # End of scope for @Crumbs
 1191: 
 1192: ############################################################
 1193: ############################################################
 1194: 
 1195: 
 1196: 1;
 1197: 
 1198: __END__

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