Annotation of loncom/interface/lonhtmlcommon.pm, revision 1.122

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

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