File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.94: download - view: text, annotated - select for diffs
Thu Oct 21 11:18:06 2004 UTC (19 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Did a bit of quoting..specifically helped out the Recently used list
when the items in the list have special characters by escape_url-ing them.

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

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