File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.107: download - view: text, annotated - select for diffs
Mon Jun 6 15:54:28 2005 UTC (19 years ago) by www
Branches: MAIN
CVS tags: HEAD
In date_setter, when falling back to "today," don't set seconds and minutes

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

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