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

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

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