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

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

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