File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.98: download - view: text, annotated - select for diffs
Tue Nov 23 14:53:05 2004 UTC (19 years, 6 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 3623: Reversed part of revision 1.94 because it was double escaping.

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

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