File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.129: download - view: text, annotated - select for diffs
Mon May 29 16:01:22 2006 UTC (17 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Ability to pick all courses always available.

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

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