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

1.2       www         1: # The LearningOnline Network with CAPA
                      2: # a pile of common html routines
                      3: #
1.253.2.5! raeburn     4: # $Id: lonhtmlcommon.pm,v 1.253.2.4 2010/10/04 19:43:30 raeburn Exp $
1.2       www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.10      matthew    28: ######################################################################
                     29: ######################################################################
                     30: 
                     31: =pod
                     32: 
                     33: =head1 NAME
                     34: 
                     35: Apache::lonhtmlcommon - routines to do common html things
                     36: 
                     37: =head1 SYNOPSIS
                     38: 
                     39: Referenced by other mod_perl Apache modules.
                     40: 
                     41: =head1 INTRODUCTION
                     42: 
                     43: lonhtmlcommon is a collection of subroutines used to present information
                     44: in a consistent html format, or provide other functionality related to
                     45: html.
                     46: 
                     47: =head2 General Subroutines
                     48: 
                     49: =over 4
                     50: 
                     51: =cut 
                     52: 
                     53: ######################################################################
                     54: ######################################################################
1.2       www        55: 
1.1       stredwic   56: package Apache::lonhtmlcommon;
                     57: 
1.104     albertel   58: use strict;
1.10      matthew    59: use Time::Local;
1.47      sakharuk   60: use Time::HiRes;
1.30      www        61: use Apache::lonlocal;
1.104     albertel   62: use Apache::lonnet;
1.130     www        63: use LONCAPA;
1.1       stredwic   64: 
1.247     www        65: 
                     66: sub coursepreflink {
                     67:    my ($text,$category)=@_;
                     68:    if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                     69:       return '<a href="/adm/courseprefs?phase=display&actions='.$category.'">'.$text.'</a>';
                     70:    } else {
                     71:       return '';
                     72:    }
                     73: }
                     74: 
1.253     www        75: sub raw_href_to_link {
                     76:    my ($message)=@_;
                     77:    $message=~s/(https?\:\/\/[^\s\'\"]+)(\s|$)/<a href="$1"><tt>$1<\/tt><\/a>$2/gi;
                     78:    return $message;
                     79: }
                     80: 
1.208     www        81: ##############################################
                     82: ##############################################
                     83: 
                     84: =pod
                     85: 
                     86: =item confirm_success
                     87: 
                     88: Successful completion of an operation message
                     89: 
                     90: =cut
                     91: 
                     92: sub confirm_success {
1.209     www        93:    my ($message,$failure)=@_;
                     94:    if ($failure) {
1.211     bisitz     95:       return '<span class="LC_error">'."\n"
1.218     bisitz     96:             .'<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.&mt('Error').'" /> '."\n"
1.211     bisitz     97:             .$message."\n"
                     98:             .'</span>'."\n";
1.209     www        99:    } else {
1.211     bisitz    100:       return '<span class="LC_success">'."\n"
1.233     raeburn   101:             .'<img src="/adm/lonIcons/navmap.correct.gif" alt="'.&mt('OK').'" /> '."\n"
1.211     bisitz    102:             .$message."\n"
                    103:             .'</span>'."\n";
1.209     www       104:    }
1.208     www       105: }
1.176     foxr      106: 
                    107: ##############################################
                    108: ##############################################
                    109: 
                    110: =pod
                    111: 
1.177     raeburn   112: =item dragmath_button
1.176     foxr      113: 
1.177     raeburn   114: Creates a button that launches a dragmath popup-window, in which an 
                    115: expression can be edited and pasted as LaTeX into a specified textarea. 
                    116: 
                    117:   textarea - Name of the textarea to edit.
                    118:   helpicon - If true, show a help icon to the right of the button.
1.176     foxr      119: 
                    120: =cut
                    121: 
1.177     raeburn   122: sub dragmath_button {
                    123:     my ($textarea,$helpicon) = @_;
                    124:     my $help_text; 
                    125:     if ($helpicon) {
                    126:         $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor');
                    127:     }
1.178     bisitz    128:     my $buttontext=&mt('Edit Math');
1.177     raeburn   129:     return <<ENDDRAGMATH;
1.246     bisitz    130:                 <input type="button" value="$buttontext" onclick="javascript:mathedit('$textarea',document)" />$help_text
1.177     raeburn   131: ENDDRAGMATH
                    132: }
                    133: 
1.176     foxr      134: ##############################################
                    135: 
1.177     raeburn   136: =pod
                    137: 
                    138: =item dragmath_js
                    139: 
                    140: Javascript used to open pop-up window containing dragmath applet which 
                    141: can be used to paste LaTeX into a textarea.
                    142:  
                    143: =cut
1.176     foxr      144: 
1.177     raeburn   145: sub dragmath_js {
1.182     foxr      146:     my ($popup) = @_;
1.177     raeburn   147:     return <<ENDDRAGMATHJS;
                    148:                 <script type="text/javascript">
1.218     bisitz    149:                 // <![CDATA[
1.176     foxr      150:                   function mathedit(textarea, doc) {
                    151:                      targetEntry = textarea;
1.177     raeburn   152:                      targetDoc   = doc;
1.182     foxr      153:                      newwin  = window.open("/adm/dragmath/applet/$popup.html","","width=565,height=500,resizable");
1.176     foxr      154:                   }
1.218     bisitz    155:                 // ]]>
1.176     foxr      156:                 </script>
1.177     raeburn   157: 
                    158: ENDDRAGMATHJS
1.176     foxr      159: }
                    160: 
1.182     foxr      161: 
1.40      www       162: ##############################################
                    163: ##############################################
                    164: 
                    165: =pod
                    166: 
                    167: =item authorbombs
                    168: 
                    169: =cut
                    170: 
                    171: ##############################################
                    172: ##############################################
                    173: 
                    174: sub authorbombs {
                    175:     my $url=shift;
                    176:     $url=&Apache::lonnet::declutter($url);
1.155     albertel  177:     my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
1.40      www       178:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
1.232     raeburn   179:     foreach my $bomb (keys(%bombs)) {
                    180: 	if ($bomb =~ /^$udom\/$uname\//) {
1.40      www       181: 	    return '<a href="/adm/bombs/'.$url.
1.218     bisitz    182: 		'"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" alt="'.&mt('Bomb').'" border="0" /></a>'.
1.40      www       183: 		&Apache::loncommon::help_open_topic('About_Bombs');
                    184: 	}
                    185:     }
                    186:     return '';
                    187: }
1.26      matthew   188: 
                    189: ##############################################
                    190: ##############################################
                    191: 
1.41      www       192: sub recent_filename {
                    193:     my $area=shift;
1.130     www       194:     return 'nohist_recent_'.&escape($area);
1.41      www       195: }
                    196: 
                    197: sub store_recent {
1.136     albertel  198:     my ($area,$name,$value,$freeze)=@_;
1.41      www       199:     my $file=&recent_filename($area);
                    200:     my %recent=&Apache::lonnet::dump($file);
1.111     www       201:     if (scalar(keys(%recent))>20) {
1.41      www       202: # remove oldest value
1.136     albertel  203: 	my $oldest=time();
1.41      www       204: 	my $delkey='';
1.136     albertel  205: 	foreach my $item (keys(%recent)) {
                    206: 	    my $thistime=(split(/\&/,$recent{$item}))[0];
                    207: 	    if (($thistime ne "always_include") && ($thistime<$oldest)) {
1.41      www       208: 		$oldest=$thistime;
1.136     albertel  209: 		$delkey=$item;
1.41      www       210: 	    }
                    211: 	}
                    212: 	&Apache::lonnet::del($file,[$delkey]);
                    213:     }
                    214: # store new value
1.136     albertel  215:     my $timestamp;
                    216:     if ($freeze) {
                    217:         $timestamp = "always_include";
                    218:     } else {
                    219:         $timestamp = time();
                    220:     }   
1.41      www       221:     &Apache::lonnet::put($file,{ $name => 
1.136     albertel  222: 				 $timestamp.'&'.&escape($value) });
1.41      www       223: }
                    224: 
1.89      banghart  225: sub remove_recent {
                    226:     my ($area,$names)=@_;
                    227:     my $file=&recent_filename($area);
                    228:     return &Apache::lonnet::del($file,$names);
                    229: }
                    230: 
1.41      www       231: sub select_recent {
                    232:     my ($area,$fieldname,$event)=@_;
                    233:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
                    234:     my $return="\n<select name='$fieldname'".
1.96      albertel  235: 	($event?" onchange='$event'":'').
1.41      www       236: 	">\n<option value=''>--- ".&mt('Recent')." ---</option>";
1.136     albertel  237:     foreach my $value (sort(keys(%recent))) {
                    238: 	unless ($value =~/^error\:/) {
                    239: 	    my $escaped = &Apache::loncommon::escape_url($value);
1.160     albertel  240: 	    &Apache::loncommon::inhibit_menu_check(\$escaped);
1.251     raeburn   241:             if ($area eq 'residx') {
                    242:                 next if ((!&Apache::lonnet::allowed('bre',$value)) && (!&Apache::lonnet::allowed('bro',$value)));
                    243:             }
1.94      foxr      244: 	    $return.="\n<option value='$escaped'>".
1.136     albertel  245: 		&unescape((split(/\&/,$recent{$value}))[1]).
1.41      www       246: 		'</option>';
                    247: 	}
                    248:     }
                    249:     $return.="\n</select>\n";
                    250:     return $return;
                    251: }
                    252: 
1.97      albertel  253: sub get_recent {
                    254:     my ($area, $n) = @_;
                    255:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
                    256: 
                    257: # Create hash with key as time and recent as value
1.136     albertel  258: # Begin filling return_hash with any 'always_include' option
1.97      albertel  259:     my %time_hash = ();
1.136     albertel  260:     my %return_hash = ();
1.232     raeburn   261:     foreach my $item (keys(%recent)) {
1.136     albertel  262:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
                    263:         if ($thistime eq 'always_include') {
                    264:             $return_hash{$item} = &unescape($thisvalue);
                    265:             $n--;
                    266:         } else {
                    267:             $time_hash{$thistime} = $item;
1.133     albertel  268:         }
1.97      albertel  269:     }
                    270: 
                    271: # Sort by decreasing time and return key value pairs
                    272:     my $idx = 1;
1.136     albertel  273:     foreach my $item (reverse(sort(keys(%time_hash)))) {
                    274:        $return_hash{$time_hash{$item}} =
                    275:                   &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
1.97      albertel  276:        if ($n && ($idx++ >= $n)) {last;}
                    277:     }
                    278: 
                    279:     return %return_hash;
                    280: }
                    281: 
1.136     albertel  282: sub get_recent_frozen {
                    283:     my ($area) = @_;
                    284:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
                    285: 
                    286: # Create hash with all 'frozen' items
                    287:     my %return_hash = ();
                    288:     foreach my $item (keys(%recent)) {
                    289:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
                    290:         if ($thistime eq 'always_include') {
                    291:             $return_hash{$item} = &unescape($thisvalue);
                    292:         }
                    293:     }
                    294:     return %return_hash;
                    295: }
                    296: 
1.97      albertel  297: 
1.41      www       298: 
1.26      matthew   299: =pod
                    300: 
                    301: =item textbox
                    302: 
                    303: =cut
                    304: 
                    305: ##############################################
                    306: ##############################################
                    307: sub textbox {
                    308:     my ($name,$value,$size,$special) = @_;
                    309:     $size = 40 if (! defined($size));
1.128     albertel  310:     $value = &HTML::Entities::encode($value,'<>&"');
1.26      matthew   311:     my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
                    312:         'value="'.$value.'" '.$special.' />';
                    313:     return $Str;
                    314: }
                    315: 
                    316: ##############################################
                    317: ##############################################
                    318: 
                    319: =pod
                    320: 
                    321: =item checkbox
                    322: 
                    323: =cut
                    324: 
                    325: ##############################################
                    326: ##############################################
                    327: sub checkbox {
1.68      matthew   328:     my ($name,$checked,$value) = @_;
                    329:     my $Str = '<input type="checkbox" name="'.$name.'" ';
                    330:     if (defined($value)) {
                    331:         $Str .= 'value="'.$value.'"';
                    332:     } 
                    333:     if ($checked) {
1.206     bisitz    334:         $Str .= ' checked="checked"';
1.68      matthew   335:     }
                    336:     $Str .= ' />';
1.26      matthew   337:     return $Str;
                    338: }
                    339: 
1.120     albertel  340: 
                    341: =pod
                    342: 
                    343: =item radiobutton
                    344: 
                    345: =cut
                    346: 
                    347: ##############################################
                    348: ##############################################
                    349: sub radio {
                    350:     my ($name,$checked,$value) = @_;
                    351:     my $Str = '<input type="radio" name="'.$name.'" ';
                    352:     if (defined($value)) {
                    353:         $Str .= 'value="'.$value.'"';
                    354:     } 
                    355:     if ($checked eq $value) {
1.206     bisitz    356:         $Str .= ' checked="checked"';
1.120     albertel  357:     }
                    358:     $Str .= ' />';
                    359:     return $Str;
                    360: }
                    361: 
1.10      matthew   362: ##############################################
                    363: ##############################################
                    364: 
                    365: =pod
                    366: 
                    367: =item &date_setter
                    368: 
1.22      matthew   369: &date_setter returns html and javascript for a compact date-setting form.
                    370: To retrieve values from it, use &get_date_from_form().
                    371: 
1.10      matthew   372: Inputs
                    373: 
                    374: =over 4
                    375: 
                    376: =item $dname 
                    377: 
                    378: The name to prepend to the form elements.  
                    379: The form elements defined will be dname_year, dname_month, dname_day,
                    380: dname_hour, dname_min, and dname_sec.
                    381: 
                    382: =item $currentvalue
                    383: 
                    384: The current setting for this time parameter.  A unix format time
                    385: (time in seconds since the beginning of Jan 1st, 1970, GMT.  
                    386: An undefined value is taken to indicate the value is the current time.
                    387: Also, to be explicit, a value of 'now' also indicates the current time.
                    388: 
1.26      matthew   389: =item $special
                    390: 
                    391: Additional html/javascript to be associated with each element in
                    392: the date_setter.  See lonparmset for example usage.
                    393: 
1.59      matthew   394: =item $includeempty 
                    395: 
                    396: =item $state
                    397: 
                    398: Specifies the initial state of the form elements.  Either 'disabled' or empty.
                    399: Defaults to empty, which indiciates the form elements are not disabled. 
                    400: 
1.22      matthew   401: =back
                    402: 
                    403: Bugs
                    404: 
                    405: The method used to restrict user input will fail in the year 2400.
                    406: 
1.10      matthew   407: =cut
                    408: 
                    409: ##############################################
                    410: ##############################################
                    411: sub date_setter {
1.67      matthew   412:     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
1.134     raeburn   413:         $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
1.175     raeburn   414:     my $now = time;
1.107     www       415:     my $wasdefined=1;
1.59      matthew   416:     if (! defined($state) || $state ne 'disabled') {
                    417:         $state = '';
                    418:     }
1.67      matthew   419:     if (! defined($no_hh_mm_ss)) {
                    420:         $no_hh_mm_ss = 0;
                    421:     }
1.110     www       422:     if ($currentvalue eq 'now') {
1.175     raeburn   423: 	$currentvalue = $now;
1.110     www       424:     }
                    425:     if ((!defined($currentvalue)) || ($currentvalue eq '')) {
                    426: 	$wasdefined=0;
                    427: 	if ($includeempty) {
                    428: 	    $currentvalue = 0;
                    429: 	} else {
1.175     raeburn   430: 	    $currentvalue = $now;
1.39      www       431: 	}
1.10      matthew   432:     }
                    433:     # other potentially useful values:     wkday,yrday,is_daylight_savings
1.175     raeburn   434:     my $tzname;
1.65      albertel  435:     my ($sec,$min,$hour,$mday,$month,$year)=('','',undef,'','','');
1.39      www       436:     if ($currentvalue) {
1.175     raeburn   437:         ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue); 
1.39      www       438:     }
1.107     www       439:     unless ($wasdefined) {
1.175     raeburn   440:         ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($now);
1.110     www       441: 	if (($defhour) || ($defmin) || ($defsec)) {
                    442: 	    $sec=($defsec?$defsec:0);
                    443: 	    $min=($defmin?$defmin:0);
                    444: 	    $hour=($defhour?$defhour:0);
                    445: 	} elsif (!$includeempty) {
                    446: 	    $sec=0;
                    447: 	    $min=0;
                    448: 	    $hour=0;
                    449: 	}
1.107     www       450:     }
1.10      matthew   451:     my $result = "\n<!-- $dname date setting form -->\n";
                    452:     $result .= <<ENDJS;
1.135     albertel  453: <script type="text/javascript">
1.218     bisitz    454: // <![CDATA[
1.10      matthew   455:     function $dname\_checkday() {
                    456:         var day   = document.$formname.$dname\_day.value;
                    457:         var month = document.$formname.$dname\_month.value;
                    458:         var year  = document.$formname.$dname\_year.value;
                    459:         var valid = true;
                    460:         if (day < 1) {
                    461:             document.$formname.$dname\_day.value = 1;
                    462:         } 
                    463:         if (day > 31) {
                    464:             document.$formname.$dname\_day.value = 31;
                    465:         }
                    466:         if ((month == 1)  || (month == 3)  || (month == 5)  ||
                    467:             (month == 7)  || (month == 8)  || (month == 10) ||
                    468:             (month == 12)) {
                    469:             if (day > 31) {
                    470:                 document.$formname.$dname\_day.value = 31;
                    471:                 day = 31;
                    472:             }
                    473:         } else if (month == 2 ) {
                    474:             if ((year % 4 == 0) && (year % 100 != 0)) {
                    475:                 if (day > 29) {
                    476:                     document.$formname.$dname\_day.value = 29;
                    477:                 }
                    478:             } else if (day > 29) {
                    479:                 document.$formname.$dname\_day.value = 28;
                    480:             }
                    481:         } else if (day > 30) {
                    482:             document.$formname.$dname\_day.value = 30;
                    483:         }
                    484:     }
1.95      matthew   485:     
1.59      matthew   486:     function $dname\_disable() {
                    487:         document.$formname.$dname\_month.disabled=true;
                    488:         document.$formname.$dname\_day.disabled=true;
                    489:         document.$formname.$dname\_year.disabled=true;
                    490:         document.$formname.$dname\_hour.disabled=true;
                    491:         document.$formname.$dname\_minute.disabled=true;
                    492:         document.$formname.$dname\_second.disabled=true;
                    493:     }
                    494: 
                    495:     function $dname\_enable() {
                    496:         document.$formname.$dname\_month.disabled=false;
                    497:         document.$formname.$dname\_day.disabled=false;
                    498:         document.$formname.$dname\_year.disabled=false;
                    499:         document.$formname.$dname\_hour.disabled=false;
                    500:         document.$formname.$dname\_minute.disabled=false;
                    501:         document.$formname.$dname\_second.disabled=false;        
                    502:     }
                    503: 
1.29      www       504:     function $dname\_opencalendar() {
1.59      matthew   505:         if (! document.$formname.$dname\_month.disabled) {
                    506:             var calwin=window.open(
1.29      www       507: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
                    508: document.$formname.$dname\_month.value+"&year="+
                    509: document.$formname.$dname\_year.value,
                    510:              "LONCAPAcal",
                    511:               "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
1.59      matthew   512:         }
1.29      www       513: 
                    514:     }
1.218     bisitz    515: // ]]>
1.10      matthew   516: </script>
                    517: ENDJS
1.192     bisitz    518:     $result .= '  <span class="LC_nobreak">';
1.96      albertel  519:     my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
1.67      matthew   520:     # Month
1.10      matthew   521:     my @Months = qw/January February  March     April   May      June 
                    522:                     July    August    September October November December/;
                    523:     # Pad @Months with a bogus value to make indexing easier
                    524:     unshift(@Months,'If you can read this an error occurred');
1.95      matthew   525:     if ($includeempty) { $monthselector.="<option value=''></option>"; }
1.10      matthew   526:     for(my $m = 1;$m <=$#Months;$m++) {
1.228     bisitz    527:         $monthselector .= qq{      <option value="$m"};
                    528:         $monthselector .= ' selected="selected"' if ($m-1 eq $month);
                    529:         $monthselector .= '> '.&mt($Months[$m]).' </option>'."\n";
1.10      matthew   530:     }
1.95      matthew   531:     $monthselector.= '  </select>';
1.67      matthew   532:     # Day
1.96      albertel  533:     my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
1.67      matthew   534:     # Year
1.226     bisitz    535:     my $yearselector = qq{<input type="text" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
1.95      matthew   536:     #
                    537:     my $hourselector = qq{<select name="$dname\_hour" $special $state >};
                    538:     if ($includeempty) { 
                    539:         $hourselector.=qq{<option value=''></option>};
                    540:     }
                    541:     for (my $h = 0;$h<24;$h++) {
1.228     bisitz    542:         $hourselector .= qq{<option value="$h"};
                    543:         $hourselector .= ' selected="selected"' if (defined($hour) && $hour == $h);
1.95      matthew   544:         $hourselector .= ">";
                    545:         my $timest='';
                    546:         if ($h == 0) {
                    547:             $timest .= "12 am";
                    548:         } elsif($h == 12) {
                    549:             $timest .= "12 noon";
                    550:         } elsif($h < 12) {
                    551:             $timest .= "$h am";
                    552:         } else {
                    553:             $timest .= $h-12 ." pm";
                    554:         }
                    555:         $timest=&mt($timest);
                    556:         $hourselector .= $timest." </option>\n";
                    557:     }
                    558:     $hourselector .= "  </select>\n";
                    559:     my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
                    560:     my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
1.134     raeburn   561:     my $cal_link;
                    562:     if (!$nolink) {
                    563:         $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
                    564:     }
1.95      matthew   565:     #
1.175     raeburn   566:     my $tzone = ' '.$tzname.' ';
1.95      matthew   567:     if ($no_hh_mm_ss) {
1.134     raeburn   568:         $result .= &mt('[_1] [_2] [_3] ',
1.174     raeburn   569:                        $monthselector,$dayselector,$yearselector).
                    570:                    $tzone;
1.134     raeburn   571:         if (!$nolink) {
1.141     albertel  572:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
1.134     raeburn   573:         }
1.95      matthew   574:     } else {
1.134     raeburn   575:         $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
                    576:                       $monthselector,$dayselector,$yearselector,
1.174     raeburn   577:                       $hourselector,$minuteselector,$secondselector).
                    578:                    $tzone;
1.134     raeburn   579:         if (!$nolink) {
1.141     albertel  580:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
1.134     raeburn   581:         }
1.67      matthew   582:     }
1.135     albertel  583:     $result .= "</span>\n<!-- end $dname date setting form -->\n";
1.10      matthew   584:     return $result;
                    585: }
                    586: 
1.175     raeburn   587: sub get_timedates {
                    588:     my ($epoch) = @_;
                    589:     my $dt = DateTime->from_epoch(epoch => $epoch)
                    590:                      ->set_time_zone(&Apache::lonlocal::gettimezone());
                    591:     my $tzname = $dt->time_zone_short_name();
                    592:     my $sec = $dt->second;
                    593:     my $min = $dt->minute;
                    594:     my $hour = $dt->hour;
                    595:     my $mday = $dt->day;
                    596:     my $month = $dt->month;
                    597:     if ($month) {
                    598:         $month --;
                    599:     }
                    600:     my $year = $dt->year;
                    601:     return ($tzname,$sec,$min,$hour,$mday,$month,$year);
                    602: }
1.166     banghart  603: 
                    604: sub build_url {
                    605:     my ($base, $fields)=@_;
                    606:     my $url;
                    607:     $url = $base.'?';
1.168     albertel  608:     foreach my $key (keys(%$fields)) {
                    609:         $url.=&escape($key).'='.&escape($$fields{$key}).'&amp;';
1.166     banghart  610:     }
                    611:     $url =~ s/&amp;$//;
                    612:     return $url;
                    613: }
                    614: 
                    615: 
1.10      matthew   616: ##############################################
                    617: ##############################################
                    618: 
1.22      matthew   619: =pod
                    620: 
1.10      matthew   621: =item &get_date_from_form
1.22      matthew   622: 
                    623: get_date_from_form retrieves the date specified in an &date_setter form.
1.10      matthew   624: 
                    625: Inputs:
                    626: 
                    627: =over 4
                    628: 
                    629: =item $dname
                    630: 
1.226     bisitz    631: The name passed to &date_setter, which prefixes the form elements.
1.10      matthew   632: 
                    633: =item $defaulttime
                    634: 
                    635: The unix time to use as the default in case of poor inputs.
                    636: 
                    637: =back
                    638: 
                    639: Returns: Unix time represented in the form.
                    640: 
                    641: =cut
                    642: 
                    643: ##############################################
                    644: ##############################################
                    645: sub get_date_from_form {
                    646:     my ($dname) = @_;
                    647:     my ($sec,$min,$hour,$day,$month,$year);
                    648:     #
1.104     albertel  649:     if (defined($env{'form.'.$dname.'_second'})) {
                    650:         my $tmpsec = $env{'form.'.$dname.'_second'};
1.10      matthew   651:         if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
                    652:             $sec = $tmpsec;
                    653:         }
1.64      albertel  654: 	if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
1.67      matthew   655:     } else {
                    656:         $sec = 0;
1.10      matthew   657:     }
1.104     albertel  658:     if (defined($env{'form.'.$dname.'_minute'})) {
                    659:         my $tmpmin = $env{'form.'.$dname.'_minute'};
1.10      matthew   660:         if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
                    661:             $min = $tmpmin;
                    662:         }
1.64      albertel  663: 	if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
1.67      matthew   664:     } else {
                    665:         $min = 0;
1.10      matthew   666:     }
1.104     albertel  667:     if (defined($env{'form.'.$dname.'_hour'})) {
                    668:         my $tmphour = $env{'form.'.$dname.'_hour'};
1.33      matthew   669:         if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
1.10      matthew   670:             $hour = $tmphour;
                    671:         }
1.67      matthew   672:     } else {
                    673:         $hour = 0;
1.10      matthew   674:     }
1.104     albertel  675:     if (defined($env{'form.'.$dname.'_day'})) {
                    676:         my $tmpday = $env{'form.'.$dname.'_day'};
1.10      matthew   677:         if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
                    678:             $day = $tmpday;
                    679:         }
                    680:     }
1.104     albertel  681:     if (defined($env{'form.'.$dname.'_month'})) {
                    682:         my $tmpmonth = $env{'form.'.$dname.'_month'};
1.10      matthew   683:         if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
1.175     raeburn   684:             $month = $tmpmonth;
1.10      matthew   685:         }
                    686:     }
1.104     albertel  687:     if (defined($env{'form.'.$dname.'_year'})) {
                    688:         my $tmpyear = $env{'form.'.$dname.'_year'};
1.175     raeburn   689:         if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
                    690:             $year = $tmpyear;
1.10      matthew   691:         }
                    692:     }
1.175     raeburn   693:     if (($year<1970) || ($year>2037)) { return undef; }
1.33      matthew   694:     if (defined($sec) && defined($min)   && defined($hour) &&
1.175     raeburn   695:         defined($day) && defined($month) && defined($year)) {
                    696:         my $timezone = &Apache::lonlocal::gettimezone();
                    697:         my $dt = DateTime->new( year   => $year,
                    698:                                 month  => $month,
                    699:                                 day    => $day,
                    700:                                 hour   => $hour,
                    701:                                 minute => $min,
                    702:                                 second => $sec,
                    703:                                 time_zone => $timezone,
                    704:                               );
                    705:         my $epoch_time  = $dt->epoch;
                    706:         if ($epoch_time ne '') {
                    707:             return $epoch_time;
                    708:         } else {
                    709:             return undef;
                    710:         }
1.10      matthew   711:     } else {
                    712:         return undef;
                    713:     }
1.20      matthew   714: }
                    715: 
                    716: ##############################################
                    717: ##############################################
                    718: 
                    719: =pod
                    720: 
                    721: =item &pjump_javascript_definition()
                    722: 
                    723: Returns javascript defining the 'pjump' function, which opens up a
                    724: parameter setting wizard.
                    725: 
                    726: =cut
                    727: 
                    728: ##############################################
                    729: ##############################################
                    730: sub pjump_javascript_definition {
                    731:     my $Str = <<END;
1.109     www       732:     function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
1.20      matthew   733:         parmwin=window.open("/adm/rat/parameter.html?type="+escape(type)
                    734:                  +"&value="+escape(value)+"&marker="+escape(marker)
                    735:                  +"&return="+escape(ret)
1.109     www       736:                  +"&call="+escape(call)+"&name="+escape(dis)
                    737:                  +"&defhour="+escape(hour)+"&defmin="+escape(min)
                    738:                  +"&defsec="+escape(sec),"LONCAPAparms",
1.20      matthew   739:                  "height=350,width=350,scrollbars=no,menubar=no");
                    740:     }
                    741: END
                    742:     return $Str;
1.10      matthew   743: }
                    744: 
                    745: ##############################################
                    746: ##############################################
1.17      matthew   747: 
                    748: =pod
                    749: 
                    750: =item &javascript_nothing()
                    751: 
                    752: Return an appropriate null for the users browser.  This is used
                    753: as the first arguement for window.open calls when you want a blank
                    754: window that you can then write to.
                    755: 
                    756: =cut
                    757: 
                    758: ##############################################
                    759: ##############################################
                    760: sub javascript_nothing {
                    761:     # mozilla and other browsers work with "''", but IE on mac does not.
                    762:     my $nothing = "''";
                    763:     my $user_browser;
                    764:     my $user_os;
1.104     albertel  765:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
                    766:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
1.17      matthew   767:     if (! defined($user_browser) || ! defined($user_os)) {
                    768:         (undef,$user_browser,undef,undef,undef,$user_os) = 
                    769:                            &Apache::loncommon::decode_user_agent();
                    770:     }
                    771:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
                    772:         $nothing = "'javascript:void(0);'";
                    773:     }
                    774:     return $nothing;
                    775: }
                    776: 
1.90      www       777: ##############################################
                    778: ##############################################
                    779: sub javascript_docopen {
1.171     albertel  780:     my ($mimetype) = @_;
                    781:     $mimetype ||= 'text/html';
1.90      www       782:     # safari does not understand document.open() and loads "text/html"
                    783:     my $nothing = "''";
                    784:     my $user_browser;
                    785:     my $user_os;
1.104     albertel  786:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
                    787:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
1.90      www       788:     if (! defined($user_browser) || ! defined($user_os)) {
                    789:         (undef,$user_browser,undef,undef,undef,$user_os) = 
                    790:                            &Apache::loncommon::decode_user_agent();
                    791:     }
                    792:     if ($user_browser eq 'safari' && $user_os =~ 'mac') {
                    793:         $nothing = "document.clear()";
                    794:     } else {
1.171     albertel  795: 	$nothing = "document.open('$mimetype','replace')";
1.90      www       796:     }
                    797:     return $nothing;
                    798: }
                    799: 
1.21      matthew   800: 
1.17      matthew   801: ##############################################
                    802: ##############################################
                    803: 
1.21      matthew   804: =pod
1.17      matthew   805: 
1.21      matthew   806: =item &StatusOptions()
1.10      matthew   807: 
1.21      matthew   808: Returns html for a selection box which allows the user to choose the
                    809: enrollment status of students.  The selection box name is 'Status'.
1.6       stredwic  810: 
1.21      matthew   811: Inputs:
1.6       stredwic  812: 
1.21      matthew   813: $status: the currently selected status.  If undefined the value of
1.104     albertel  814: $env{'form.Status'} is taken.  If that is undefined, a value of 'Active'
1.21      matthew   815: is used.
1.6       stredwic  816: 
1.21      matthew   817: $formname: The name of the form.  If defined the onchange attribute of
                    818: the selection box is set to document.$formname.submit().
1.6       stredwic  819: 
1.21      matthew   820: $size: the size (number of lines) of the selection box.
1.6       stredwic  821: 
1.27      matthew   822: $onchange: javascript to use when the value is changed.  Enclosed in 
                    823: double quotes, ""s, not single quotes.
                    824: 
1.21      matthew   825: Returns: a perl string as described.
1.1       stredwic  826: 
1.21      matthew   827: =cut
1.9       stredwic  828: 
1.21      matthew   829: ##############################################
                    830: ##############################################
                    831: sub StatusOptions {
1.165     banghart  832:     my ($status, $formName,$size,$onchange,$mult)=@_;
1.21      matthew   833:     $size = 1 if (!defined($size));
                    834:     if (! defined($status)) {
                    835:         $status = 'Active';
1.104     albertel  836:         $status = $env{'form.Status'} if (exists($env{'form.Status'}));
1.9       stredwic  837:     }
1.1       stredwic  838: 
                    839:     my $Str = '';
                    840:     $Str .= '<select name="Status"';
1.165     banghart  841:     if (defined($mult)){
                    842:         $Str .= ' multiple="multiple" ';
                    843:     }
1.27      matthew   844:     if(defined($formName) && $formName ne '' && ! defined($onchange)) {
1.1       stredwic  845:         $Str .= ' onchange="document.'.$formName.'.submit()"';
1.27      matthew   846:     }
                    847:     if (defined($onchange)) {
                    848:         $Str .= ' onchange="'.$onchange.'"';
1.1       stredwic  849:     }
1.21      matthew   850:     $Str .= ' size="'.$size.'" ';
1.1       stredwic  851:     $Str .= '>'."\n";
1.153     raeburn   852:     foreach my $type (['Active',  &mt('Currently Has Access')],
                    853: 		      ['Future',  &mt('Will Have Future Access')],
                    854: 		      ['Expired', &mt('Previously Had Access')],
                    855: 		      ['Any',     &mt('Any Access Status')]) {
1.151     albertel  856: 	my ($name,$label) = @$type;
                    857: 	$Str .= '<option value="'.$name.'" ';
                    858: 	if ($status eq $name) {
                    859: 	    $Str .= 'selected="selected" ';
                    860: 	}
                    861: 	$Str .= '>'.$label.'</option>'."\n";
                    862:     }
                    863: 
1.1       stredwic  864:     $Str .= '</select>'."\n";
1.7       stredwic  865: }
1.12      matthew   866: 
                    867: ########################################################
                    868: ########################################################
1.7       stredwic  869: 
1.23      matthew   870: =pod
                    871: 
                    872: =item Progess Window Handling Routines
                    873: 
                    874: These routines handle the creation, update, increment, and closure of 
                    875: progress windows.  The progress window reports to the user the number
                    876: of items completed and an estimate of the time required to complete the rest.
                    877: 
                    878: =over 4
                    879: 
                    880: 
                    881: =item &Create_PrgWin
                    882: 
                    883: Writes javascript to the client to open a progress window and returns a
                    884: data structure used for bookkeeping.
                    885: 
                    886: Inputs
                    887: 
                    888: =over 4
                    889: 
                    890: =item $r Apache request
                    891: 
                    892: =item $title The title of the progress window
                    893: 
                    894: =item $heading A description (usually 1 line) of the process being initiated.
                    895: 
                    896: =item $number_to_do The total number of items being processed.
1.50      albertel  897: 
                    898: =item $type Either 'popup' or 'inline' (popup is assumed if nothing is
                    899:        specified)
                    900: 
1.51      albertel  901: =item $width Specify the width in charaters of the input field.
                    902: 
1.50      albertel  903: =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
                    904: 
                    905: =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   906: 
                    907: =back
                    908: 
                    909: Returns a hash containing the progress state data structure.
                    910: 
                    911: 
                    912: =item &Update_PrgWin
                    913: 
                    914: Updates the text in the progress indicator.  Does not increment the count.
                    915: See &Increment_PrgWin.
                    916: 
                    917: Inputs:
                    918: 
                    919: =over 4
                    920: 
                    921: =item $r Apache request
                    922: 
                    923: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
                    924: 
                    925: =item $displaystring The string to write to the status indicator
                    926: 
                    927: =back
                    928: 
                    929: Returns: none
                    930: 
                    931: 
                    932: =item Increment_PrgWin
                    933: 
                    934: Increment the count of items completed for the progress window by 1.  
                    935: 
                    936: Inputs:
                    937: 
                    938: =over 4
                    939: 
                    940: =item $r Apache request
                    941: 
                    942: =item $prog_state Pointer to the data structure returned by Create_PrgWin
                    943: 
                    944: =item $extraInfo A description of the items being iterated over.  Typically
                    945: 'student'.
                    946: 
                    947: =back
                    948: 
                    949: Returns: none
                    950: 
                    951: 
                    952: =item Close_PrgWin
                    953: 
                    954: Closes the progress window.
                    955: 
                    956: Inputs:
                    957: 
                    958: =over 4 
                    959: 
                    960: =item $r Apache request
                    961: 
                    962: =item $prog_state Pointer to the data structure returned by Create_PrgWin
                    963: 
                    964: =back
                    965: 
                    966: Returns: none
                    967: 
                    968: =back
                    969: 
                    970: =cut
                    971: 
                    972: ########################################################
                    973: ########################################################
                    974: 
1.51      albertel  975: my $uniq=0;
                    976: sub get_uniq_name {
                    977:     $uniq++;
                    978:     return 'uniquename'.$uniq;
                    979: }
                    980: 
1.7       stredwic  981: # Create progress
                    982: sub Create_PrgWin {
1.51      albertel  983:     my ($r, $title, $heading, $number_to_do,$type,$width,$formname,
                    984: 	$inputname)=@_;
1.49      albertel  985:     if (!defined($type)) { $type='popup'; }
1.51      albertel  986:     if (!defined($width)) { $width=55; }
1.49      albertel  987:     my %prog_state;
                    988:     $prog_state{'type'}=$type;
                    989:     if ($type eq 'popup') {
                    990: 	$prog_state{'window'}='popwin';
1.122     albertel  991: 	my $start_page =
                    992: 	    &Apache::loncommon::start_page($title,undef,
                    993: 					   {'only_body' => 1,
                    994: 					    'bgcolor'   => '#88DDFF',
                    995: 					    'js_ready'  => 1});
                    996: 	my $end_page = &Apache::loncommon::end_page({'js_ready'  => 1});
                    997: 
1.49      albertel  998: 	#the whole function called through timeout is due to issues
                    999: 	#in mozilla Read BUG #2665 if you want to know the whole story
1.230     bisitz   1000: 	&r_print($r,&Apache::lonhtmlcommon::scripttag(
1.49      albertel 1001:         "var popwin;
                   1002:          function openpopwin () {
                   1003:          popwin=open(\'\',\'popwin\',\'width=400,height=100\');".
1.122     albertel 1004:         "popwin.document.writeln(\'".$start_page.
1.170     albertel 1005:               "<h4>".&mt("$heading")."<\/h4>".
1.212     bisitz   1006:               "<form action=\"\" name=\"popremain\" method=\"post\">".
1.51      albertel 1007:               '<input type="text" size="'.$width.'" name="remaining" value="'.
1.131     albertel 1008: 	      &mt('Starting').'" /><\\/form>'.$end_page.
1.122     albertel 1009:               "\');".
1.49      albertel 1010:         "popwin.document.close();}".
1.230     bisitz   1011:         "\nwindow.setTimeout(openpopwin,0)"
                   1012:     ));
1.49      albertel 1013: 	$prog_state{'formname'}='popremain';
                   1014: 	$prog_state{'inputname'}="remaining";
                   1015:     } elsif ($type eq 'inline') {
                   1016: 	$prog_state{'window'}='window';
                   1017: 	if (!$formname) {
1.51      albertel 1018: 	    $prog_state{'formname'}=&get_uniq_name();
1.159     banghart 1019: 	    &r_print($r,'<form action="" name="'.$prog_state{'formname'}.'">');
1.49      albertel 1020: 	} else {
                   1021: 	    $prog_state{'formname'}=$formname;
                   1022: 	}
                   1023: 	if (!$inputname) {
1.51      albertel 1024: 	    $prog_state{'inputname'}=&get_uniq_name();
1.170     albertel 1025: 	    &r_print($r,&mt("$heading [_1]",' <input type="text" name="'.$prog_state{'inputname'}.'" size="'.$width.'" />'));
1.49      albertel 1026: 	} else {
                   1027: 	    $prog_state{'inputname'}=$inputname;
                   1028: 	    
                   1029: 	}
                   1030: 	if (!$formname) { &r_print($r,'</form>'); }
                   1031: 	&Update_PrgWin($r,\%prog_state,&mt('Starting'));
                   1032:     }
1.7       stredwic 1033: 
1.16      albertel 1034:     $prog_state{'done'}=0;
1.23      matthew  1035:     $prog_state{'firststart'}=&Time::HiRes::time();
                   1036:     $prog_state{'laststart'}=&Time::HiRes::time();
1.16      albertel 1037:     $prog_state{'max'}=$number_to_do;
1.49      albertel 1038:     
1.14      albertel 1039:     return %prog_state;
1.7       stredwic 1040: }
                   1041: 
                   1042: # update progress
                   1043: sub Update_PrgWin {
1.14      albertel 1044:     my ($r,$prog_state,$displayString)=@_;
1.230     bisitz   1045:     &r_print($r,&Apache::lonhtmlcommon::scripttag(
1.218     bisitz   1046:         $$prog_state{'window'}.'.document.'.
1.230     bisitz   1047:         $$prog_state{'formname'}.'.'.
                   1048:         $$prog_state{'inputname'}.'.value="'.
                   1049:         $displayString.'";'
                   1050:     ));
1.23      matthew  1051:     $$prog_state{'laststart'}=&Time::HiRes::time();
1.14      albertel 1052: }
                   1053: 
                   1054: # increment progress state
                   1055: sub Increment_PrgWin {
                   1056:     my ($r,$prog_state,$extraInfo)=@_;
1.16      albertel 1057:     $$prog_state{'done'}++;
1.23      matthew  1058:     my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
                   1059:         $$prog_state{'done'} *
1.16      albertel 1060: 	($$prog_state{'max'}-$$prog_state{'done'});
                   1061:     $time_est = int($time_est);
1.80      matthew  1062:     #
                   1063:     my $min = int($time_est/60);
                   1064:     my $sec = $time_est % 60;
                   1065:     # 
                   1066:     my $str;
1.91      albertel 1067:     if ($min == 0 && $sec > 1) {
1.80      matthew  1068:         $str = '[_2] seconds';
1.91      albertel 1069:     } elsif ($min == 1 && $sec > 1) {
                   1070:         $str = '1 minute [_2] seconds';
1.80      matthew  1071:     } elsif ($min == 1 && $sec < 2) {
                   1072:         $str = '1 minute';
                   1073:     } elsif ($min < 10 && $sec > 1) {
                   1074:         $str = '[_1] minutes, [_2] seconds';
1.81      matthew  1075:     } elsif ($min >= 10 || $sec < 2) {
1.80      matthew  1076:         $str = '[_1] minutes';
1.16      albertel 1077:     }
1.80      matthew  1078:     $time_est = &mt($str,$min,$sec);
                   1079:     #
1.23      matthew  1080:     my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
                   1081:     if ($lasttime > 9) {
                   1082:         $lasttime = int($lasttime);
                   1083:     } elsif ($lasttime < 0.01) {
                   1084:         $lasttime = 0;
                   1085:     } else {
                   1086:         $lasttime = sprintf("%3.2f",$lasttime);
                   1087:     }
1.19      matthew  1088:     if ($lasttime == 1) {
1.32      www      1089:         $lasttime = '('.$lasttime.' '.&mt('second for').' '.$extraInfo.')';
1.19      matthew  1090:     } else {
1.32      www      1091:         $lasttime = '('.$lasttime.' '.&mt('seconds for').' '.$extraInfo.')';
1.28      matthew  1092:     }
                   1093:     #
1.104     albertel 1094:     my $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
                   1095:     my $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
1.28      matthew  1096:     if (! defined($user_browser) || ! defined($user_os)) {
                   1097:         (undef,$user_browser,undef,undef,undef,$user_os) = 
                   1098:                            &Apache::loncommon::decode_user_agent();
                   1099:     }
                   1100:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
                   1101:         $lasttime = '';
1.19      matthew  1102:     }
1.230     bisitz   1103:     &r_print($r,&Apache::lonhtmlcommon::scripttag(
1.218     bisitz   1104:         $$prog_state{'window'}.'.document.'.
1.230     bisitz   1105:         $$prog_state{'formname'}.'.'.
                   1106:         $$prog_state{'inputname'}.'.value="'.
                   1107:         $$prog_state{'done'}.'/'.$$prog_state{'max'}.
                   1108:         ': '.$time_est.' '.&mt('remaining').' '.$lasttime.'";'
                   1109:     ));
1.23      matthew  1110:     $$prog_state{'laststart'}=&Time::HiRes::time();
1.7       stredwic 1111: }
                   1112: 
                   1113: # close Progress Line
                   1114: sub Close_PrgWin {
1.14      albertel 1115:     my ($r,$prog_state)=@_;
1.49      albertel 1116:     if ($$prog_state{'type'} eq 'popup') {
1.230     bisitz   1117:         &r_print($r,&Apache::lonhtmlcommon::scripttag(
                   1118:             'popwin.close()'
                   1119:         ));
1.49      albertel 1120:     } elsif ($$prog_state{'type'} eq 'inline') {
                   1121: 	&Update_PrgWin($r,$prog_state,&mt('Done'));
                   1122:     }
1.48      albertel 1123:     undef(%$prog_state);
                   1124: }
                   1125: 
                   1126: sub r_print {
                   1127:     my ($r,$to_print)=@_;
                   1128:     if ($r) {
                   1129: 	$r->print($to_print);
                   1130: 	$r->rflush();
1.47      sakharuk 1131:     } else {
1.48      albertel 1132: 	print($to_print);
1.47      sakharuk 1133:     }
1.1       stredwic 1134: }
1.34      www      1135: 
                   1136: # ------------------------------------------------------- Puts directory header
                   1137: 
                   1138: sub crumbs {
1.252     bisitz   1139:     my ($uri,$target,$prefix,$form,$skiplast)=@_;
1.100     raeburn  1140:     if ($target) {
                   1141:         $target = ' target="'.
                   1142:                   &Apache::loncommon::escape_single($target).'"';
                   1143:     }
1.252     bisitz   1144:     my $output='<span class="LC_filename">';
                   1145:     $output.=$prefix.'/';
1.249     raeburn  1146:     if (($env{'user.adv'}) || ($env{'user.author'})) {
1.252     bisitz   1147:         my $path=$prefix.'/';
                   1148:         foreach my $dir (split('/',$uri)) {
1.99      matthew  1149:             if (! $dir) { next; }
                   1150:             $path .= $dir;
1.252     bisitz   1151:             if ($path eq $uri) {
                   1152:                 if ($skiplast) {
                   1153:                     $output.=$dir;
1.132     www      1154:                     last;
1.252     bisitz   1155:                 } 
                   1156:             } else {
                   1157:                 $path.='/'; 
                   1158:             }
1.157     albertel 1159:             my $href_path = &HTML::Entities::encode($path,'<>&"');
1.252     bisitz   1160:             &Apache::loncommon::inhibit_menu_check(\$href_path);
                   1161:             if ($form) {
                   1162:                 my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
                   1163:                 $output.=qq{<a href="$href"$target>$dir</a>/};
                   1164:             } else {
                   1165:                 $output.=qq{<a href="$href_path"$target>$dir</a>/};
                   1166:             }
                   1167:         }
1.35      www      1168:     } else {
1.252     bisitz   1169:         foreach my $dir (split('/',$uri)) {
1.149     albertel 1170:             if (! $dir) { next; }
1.252     bisitz   1171:             $output.=$dir.'/';
                   1172:         }
1.34      www      1173:     }
1.149     albertel 1174:     if ($uri !~ m|/$|) { $output=~s|/$||; }
1.252     bisitz   1175:     $output.='</span>';
                   1176: 
                   1177:     return $output;
1.34      www      1178: }
                   1179: 
1.85      www      1180: # --------------------- A function that generates a window for the spellchecker
                   1181: 
                   1182: sub spellheader {
1.123     albertel 1183:     my $start_page=
                   1184: 	&Apache::loncommon::start_page('Speller Suggestions',undef,
1.140     albertel 1185: 				       {'only_body'   => 1,
                   1186: 					'js_ready'    => 1,
                   1187: 					'bgcolor'     => '#DDDDDD',
                   1188: 				        'add_entries' => {
                   1189: 					    'onload' => 
                   1190:                                                'document.forms.spellcheckform.submit()',
                   1191:                                              }
                   1192: 				        });
1.123     albertel 1193:     my $end_page=
                   1194: 	&Apache::loncommon::end_page({'js_ready'  => 1}); 
                   1195: 
1.105     www      1196:     my $nothing=&javascript_nothing();
1.85      www      1197:     return (<<ENDCHECK);
                   1198: <script type="text/javascript"> 
1.218     bisitz   1199: // <![CDATA[
1.92      albertel 1200: //<!-- BEGIN LON-CAPA Internal
1.85      www      1201: var checkwin;
                   1202: 
1.140     albertel 1203: function spellcheckerwindow(string) {
                   1204:     var esc_string = string.replace(/\"/g,'&quot;');
1.105     www      1205:     checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
1.154     albertel 1206:     checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
1.85      www      1207:     checkwin.document.close();
                   1208: }
1.92      albertel 1209: // END LON-CAPA Internal -->
1.218     bisitz   1210: // ]]>
1.85      www      1211: </script>
                   1212: ENDCHECK
                   1213: }
                   1214: 
                   1215: # ---------------------------------- Generate link to spell checker for a field
                   1216: 
                   1217: sub spelllink {
                   1218:     my ($form,$field)=@_;
                   1219:     my $linktext=&mt('Check Spelling');
                   1220:     return (<<ENDLINK);
1.140     albertel 1221: <a href="javascript:if (typeof(document.$form.onsubmit)!='undefined') { if (document.$form.onsubmit!=null) { document.$form.onsubmit();}};spellcheckerwindow(this.document.forms.$form.$field.value);">$linktext</a>
1.85      www      1222: ENDLINK
                   1223: }
                   1224: 
1.52      www      1225: # ------------------------------------------------- Output headers for HTMLArea
                   1226: 
1.124     albertel 1227: {
                   1228:     my @htmlareafields;
                   1229:     sub init_htmlareafields {
                   1230: 	undef(@htmlareafields);
                   1231:     }
                   1232:     
                   1233:     sub add_htmlareafields {
                   1234: 	my (@newfields) = @_;
                   1235: 	push(@htmlareafields,@newfields);
                   1236:     }
                   1237: 
                   1238:     sub get_htmlareafields {
                   1239: 	return @htmlareafields;
                   1240:     }
                   1241: }
                   1242: 
1.52      www      1243: sub htmlareaheaders {
1.167     albertel 1244:     return if (&htmlareablocked());
                   1245:     return if (!&htmlareabrowser());
1.52      www      1246:     return (<<ENDHEADERS);
1.167     albertel 1247: <script type="text/javascript" src="/fckeditor/fckeditor.js"></script>
1.52      www      1248: ENDHEADERS
                   1249: }
                   1250: 
1.76      www      1251: # ----------------------------------------------------------------- Preferences
                   1252: 
                   1253: sub disablelink {
1.77      www      1254:     my @fields=@_;
                   1255:     if (defined($#fields)) {
                   1256: 	unless ($#fields>=0) { return ''; }
                   1257:     }
1.130     www      1258:     return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=off&returnurl=','<>&"').&escape($ENV{'REQUEST_URI'}).'">'.&mt('Disable WYSIWYG Editor').'</a>';
1.76      www      1259: }
                   1260: 
                   1261: sub enablelink {
1.77      www      1262:     my @fields=@_;
                   1263:     if (defined($#fields)) {
                   1264: 	unless ($#fields>=0) { return ''; }
                   1265:     }
1.130     www      1266:     return '<a href="'.&HTML::Entities::encode('/adm/preferences?action=set_wysiwyg&wysiwyg=on&returnurl=','<>&"').&escape($ENV{'REQUEST_URI'}).'">'.&mt('Enable WYSIWYG Editor').'</a>';
1.76      www      1267: }
                   1268: 
1.167     albertel 1269: # ------------------------------------------------- lang to use in html editor
                   1270: sub htmlarea_lang {
                   1271:     my $lang='en';
                   1272:     if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
                   1273: 	$lang=&mt('htmlarea_lang');
                   1274:     }
                   1275:     return $lang;
                   1276: }
                   1277: 
1.72      www      1278: # ----------------------------------------- Script to activate only some fields
                   1279: 
                   1280: sub htmlareaselectactive {
1.73      www      1281:     my @fields=@_;
1.76      www      1282:     unless (&htmlareabrowser()) { return ''; }
1.77      www      1283:     if (&htmlareablocked()) { return '<br />'.&enablelink(@fields); }
1.230     bisitz   1284:     my $output='<script type="text/javascript" defer="1">'."\n"
                   1285:               .'// <![CDATA['."\n";
1.167     albertel 1286:     my $lang = &htmlarea_lang();
                   1287:     foreach my $field (@fields) {
                   1288: 	$output.="
                   1289: {
                   1290:     var oFCKeditor = new FCKeditor('$field');
                   1291:     oFCKeditor.Config['CustomConfigurationsPath'] = 
                   1292: 	'/fckeditor/loncapaconfig.js';    
                   1293:     oFCKeditor.ReplaceTextarea();
                   1294:     oFCKeditor.Config['AutoDetectLanguage'] = false;
                   1295:     oFCKeditor.Config['DefaultLanguage'] = '$lang';
                   1296: }";
1.72      www      1297:     }
1.218     bisitz   1298:     $output.="\nwindow.status='Activated Editfields';\n"
1.230     bisitz   1299:             .'// ]]>'."\n"
1.218     bisitz   1300:             .'</script><br />'.
1.77      www      1301: 	&disablelink(@fields);
1.72      www      1302:     return $output;
                   1303: }
                   1304: 
1.61      www      1305: # --------------------------------------------------------------------- Blocked
                   1306: 
                   1307: sub htmlareablocked {
1.104     albertel 1308:     unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
1.71      www      1309:     return 0;
1.52      www      1310: }
                   1311: 
                   1312: # ---------------------------------------- Browser capable of running HTMLArea?
                   1313: 
                   1314: sub htmlareabrowser {
                   1315:     return 1;
                   1316: }
1.53      matthew  1317: 
                   1318: ############################################################
                   1319: ############################################################
                   1320: 
                   1321: =pod
                   1322: 
                   1323: =item breadcrumbs
                   1324: 
                   1325: Compiles the previously registered breadcrumbs into an series of links.
                   1326: Additionally supports a 'component', which will be displayed on the
1.223     droeschl 1327: right side of the breadcrumbs enclosing div (without a link).
1.53      matthew  1328: A link to help for the component will be included if one is specified.
                   1329: 
                   1330: All inputs can be undef without problems.
                   1331: 
1.223     droeschl 1332: Inputs: $component (the text on the right side of the breadcrumbs trail),
1.53      matthew  1333:         $component_help
1.63      albertel 1334:         $menulink (boolean, controls whether to include a link to /adm/menu)
1.138     albertel 1335:         $helplink (if 'nohelp' don't include the orange help link)
                   1336:         $css_class (optional name for the class to apply to the table for CSS)
1.197     raeburn  1337:         $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component
                   1338:            when including the text on the right.
1.53      matthew  1339: Returns a string containing breadcrumbs for the current page.
                   1340: 
                   1341: =item clear_breadcrumbs
                   1342: 
                   1343: Clears the previously stored breadcrumbs.
                   1344: 
                   1345: =item add_breadcrumb
                   1346: 
                   1347: Pushes a breadcrumb on the stack of crumbs.
                   1348: 
                   1349: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
                   1350: are required.  If present the keys 'faq' and 'bug' will be used to provide
1.156     albertel 1351: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' 
                   1352: and 'text' values won't be sent through &mt()
1.53      matthew  1353: 
                   1354: returns: nothing    
                   1355: 
                   1356: =cut
                   1357: 
                   1358: ############################################################
                   1359: ############################################################
                   1360: {
                   1361:     my @Crumbs;
1.242     droeschl 1362:     my %tools = ();
1.57      matthew  1363:     
1.53      matthew  1364:     sub breadcrumbs {
1.216     bisitz   1365:         my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, $CourseBreadcrumbs) = @_;
1.53      matthew  1366:         #
1.215     droeschl 1367:         $css_class ||= 'LC_breadcrumbs';
1.205     amueller 1368: 
1.57      matthew  1369:         # Make the faq and bug data cascade
1.223     droeschl 1370:         my $faq  = '';
                   1371:         my $bug  = '';
                   1372:         my $help = '';
1.215     droeschl 1373:         # Crumb Symbol
1.223     droeschl 1374:         my $crumbsymbol = '&raquo;';
1.60      www      1375:         # The last breadcrumb does not have a link, so handle it separately.
1.53      matthew  1376:         my $last = pop(@Crumbs);
1.57      matthew  1377:         #
1.70      matthew  1378:         # The first one should be the course or a menu link
1.215     droeschl 1379:         if (!defined($menulink)) { $menulink=1; }
1.70      matthew  1380:         if ($menulink) {
1.253.2.2  raeburn  1381:             if ($menulink eq '_nomenu') {
                   1382:                 return unless($last);
                   1383:             } else {
1.253.2.1  raeburn  1384:                 my $description = 'Menu';
1.253.2.4  raeburn  1385:                 my $href = '/adm/menu';
                   1386:                 my $tooltip = 'Go to main menu';
1.253.2.1  raeburn  1387:                 my $no_mt_descr = 0;
1.253.2.3  raeburn  1388:                 if ((exists($env{'request.course.id'})) &&
1.253.2.5! raeburn  1389:                     ($env{'request.course.id'} ne '') && 
        !          1390:                     !($env{'form.context'} eq 'requestcrs')) {
1.253.2.4  raeburn  1391:                     if ((&Apache::loncommon::needs_gci_custom()) || ($env{'user.domain'} eq 'gcitest')) {
1.253.2.5! raeburn  1392:                         if ($env{'environment.remotenavmap'} eq 'on') {
        !          1393:                             # open link using javascript when remote navmap is activated
        !          1394:                             $href = "javascript:gonav('/adm/navmaps');";
        !          1395:                         } else {
        !          1396:                             $href = '/adm/navmaps';
        !          1397:                         }
1.253.2.4  raeburn  1398:                         $tooltip = 'Contents';
                   1399:                     }
                   1400:                     if ($env{'course.'.$env{'request.course.id'}.'.description'} ne '') {
                   1401:                         $description =
                   1402:                             $env{'course.'.$env{'request.course.id'}.'.description'};
                   1403:                         $no_mt_descr = 1;
                   1404:                     }
1.253.2.3  raeburn  1405:                 }
1.253.2.4  raeburn  1406:                 $menulink =  {  href   => $href,
                   1407:                                 title  => $tooltip,
                   1408:                                 target => '_top',
                   1409:                                 text   => $description,
                   1410:                                 no_mt  => $no_mt_descr, };
                   1411:                 if ($last) {
1.253.2.2  raeburn  1412:                     #$last set, so we have some crumbs
                   1413:                     unshift(@Crumbs,$menulink);
                   1414:                 } else {
                   1415:                     #only menulink crumb present
                   1416:                     $last = $menulink;
                   1417:                 }
1.215     droeschl 1418:             }
1.53      matthew  1419:         }
1.219     droeschl 1420:         my $links = join "", 
1.53      matthew  1421:                  map {
1.219     droeschl 1422:                      $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
                   1423:                      $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
1.106     www      1424:                      $help = $_->{'help'} if (exists($_->{'help'}));
1.219     droeschl 1425: 
1.253.2.3  raeburn  1426:                      my $result = $_->{no_mt} ? $_->{text} : mt($_->{text});
                   1427: 
                   1428:                      if ($_->{href}){
                   1429:                          $result = htmltag( 'a', $result, 
1.219     droeschl 1430:                                            { 
                   1431:                                                href   => $_->{href},
1.223     droeschl 1432:                                                title  => $_->{no_mt} ? 
                   1433:                                                 $_->{title} : mt($_->{title}),
1.219     droeschl 1434:                                                target => $_->{target},
                   1435:                                            });
1.253.2.3  raeburn  1436:                      }
                   1437: 
1.223     droeschl 1438:                      $result = htmltag( 'li', "$result $crumbsymbol");
1.253.2.3  raeburn  1439:                  } @Crumbs;
1.223     droeschl 1440: 
                   1441:         #should the last Element be translated?
1.253.2.3  raeburn  1442: 
                   1443:         my $lasttext = $last->{'no_mt'} ? $last->{'text'}
                   1444:                      : mt( $last->{'text'} );
                   1445: 
                   1446:         # last breadcrumb is the first order heading of a page
                   1447:         # for course breadcrumbs it's just bold
                   1448:         $links .= htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
1.253.2.4  raeburn  1449:                            $lasttext), {title => $lasttext});
1.223     droeschl 1450: 
1.54      matthew  1451:         my $icons = '';
1.223     droeschl 1452:         $faq  = $last->{'faq'}  if (exists($last->{'faq'}));
                   1453:         $bug  = $last->{'bug'}  if (exists($last->{'bug'}));
1.106     www      1454:         $help = $last->{'help'} if (exists($last->{'help'}));
                   1455:         $component_help=($component_help?$component_help:$help);
1.145     albertel 1456: #        if ($faq ne '') {
                   1457: #            $icons .= &Apache::loncommon::help_open_faq($faq);
                   1458: #        }
1.79      raeburn  1459: #        if ($bug ne '') {
                   1460: #            $icons .= &Apache::loncommon::help_open_bug($bug);
                   1461: #        }
1.223     droeschl 1462:         if ($faq ne '' || $component_help ne '' || $bug ne '') {
                   1463:             $icons .= &Apache::loncommon::help_open_menu($component,
                   1464:                                                          $component_help,
                   1465:                                                          $faq,$bug);
                   1466:         }
1.54      matthew  1467:         #
1.205     amueller 1468: 		
                   1469: 
1.223     droeschl 1470:         unless ($CourseBreadcrumbs) {
                   1471:             $links = htmltag('ol',  $links, { id => "LC_MenuBreadcrumbs"   });
                   1472:         } else {
1.227     bisitz   1473:             $links = htmltag('ul',  $links, { class => "LC_CourseBreadcrumbs" });
1.53      matthew  1474:         }
1.223     droeschl 1475: 
                   1476:         if ($component) {
                   1477:             $links = htmltag('span', 
                   1478:                              ( $no_mt ? $component : mt($component) ).
                   1479:                              ( $icons ? $icons : '' ),
                   1480:                              { class => 'LC_breadcrumbs_component' } )
                   1481:                              .$links;
                   1482:         }
                   1483:         
1.253.2.3  raeburn  1484:         render_tools(\$links);
1.223     droeschl 1485:         $links = htmltag('div', $links, 
1.225     bisitz   1486:                         { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ;
1.253.2.3  raeburn  1487:         render_advtools(\$links);
1.223     droeschl 1488: 
1.53      matthew  1489:         # Return the @Crumbs stack to what we started with
                   1490:         push(@Crumbs,$last);
                   1491:         shift(@Crumbs);
1.223     droeschl 1492:         # Return the breadcrumb's line
                   1493:         return "$links";
1.53      matthew  1494:     }
                   1495: 
                   1496:     sub clear_breadcrumbs {
                   1497:         undef(@Crumbs);
1.242     droeschl 1498:         undef(%tools);
1.53      matthew  1499:     }
                   1500: 
                   1501:     sub add_breadcrumb {
1.232     raeburn  1502:         push(@Crumbs,@_);
1.53      matthew  1503:     }
1.242     droeschl 1504:     
1.253.2.3  raeburn  1505: =item add_breadcrumb_tool($category, $html)
                   1506: 
                   1507: Adds $html to $category of the breadcrumb toolbar container.
                   1508: 
                   1509: $html is usually a link to a page that invokes a function on the currently
                   1510: displayed data (e.g. print when viewing a problem)
                   1511: 
                   1512: Currently there are 3 possible values for $category:
                   1513: 
                   1514: =over
                   1515: 
                   1516: =item navigation
                   1517: left of breadcrumbs line
                   1518: 
                   1519: =item tools
                   1520: right of breadcrumbs line
                   1521: 
                   1522: =item advtools
                   1523: advanced tools shown in a separate box below breadcrumbs line
                   1524: 
                   1525: =back
                   1526: 
                   1527: returns: nothing
                   1528: 
                   1529: =cut
1.242     droeschl 1530: 
                   1531:     sub add_breadcrumb_tool {
1.253.2.3  raeburn  1532:         my ($category, @html) = @_;
                   1533:         return unless @html;
                   1534:         if (!defined(%tools)) {
                   1535:             %tools = ( navigation => [], tools => [], advtools => []);
                   1536:         }
                   1537: 
                   1538:         #this cleans data received from lonmenu::innerregister
                   1539:         @html = grep {defined $_ && $_ ne ''} @html;
                   1540:         for (@html) {
                   1541:             s/align="(right|left)"//;
                   1542:             s/<span.*?\/span>// if $category ne 'advtools';
1.242     droeschl 1543:         }
1.253.2.3  raeburn  1544: 
                   1545:         push @{$tools{$category}}, @html;
1.242     droeschl 1546:     }
                   1547: 
1.253.2.3  raeburn  1548: =item clear_breadcrumb_tools()
                   1549: 
                   1550: Clears the breadcrumb toolbar container.
                   1551: 
                   1552: returns: nothing
                   1553: 
                   1554: =cut
                   1555: 
1.245     droeschl 1556:     sub clear_breadcrumb_tools {
                   1557:         undef(%tools);
                   1558:     }
                   1559: 
1.253.2.3  raeburn  1560: =item render_tools(\$breadcrumbs)
                   1561: 
                   1562: Creates html for breadcrumb tools (categories navigation and tools) and inserts
                   1563: \$breadcrumbs at the correct position.
                   1564: 
                   1565: input: \$breadcrumbs - a reference to the string containing prepared
                   1566: breadcrumbs.
                   1567: 
                   1568: returns: nothing
                   1569: =cut
                   1570: 
                   1571: #TODO might split this in separate functions for each category
                   1572:     sub render_tools {
                   1573:         my ($breadcrumbs) = @_;
1.242     droeschl 1574:         return unless defined %tools;
1.253.2.3  raeburn  1575: 
                   1576:         my $navigation = list_from_array($tools{navigation},
                   1577:                    { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
                   1578:         my $tools = list_from_array($tools{tools},
                   1579:                    { listattr => { class=>"LC_breadcrumb_tools_tools" } });
                   1580:         $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs],
                   1581:                    { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
                   1582:     }
                   1583: 
1.253.2.4  raeburn  1584: =item render_advtools(\$breadcrumbs,$legend)
1.253.2.3  raeburn  1585: 
                   1586: Creates html for advanced tools (category advtools) and inserts \$breadcrumbs
                   1587: at the correct position.
                   1588: 
                   1589: input: \$breadcrumbs - a reference to the string containing prepared
                   1590: breadcrumbs (after render_tools call).
                   1591: 
                   1592: returns: nothing
                   1593: =cut
                   1594: 
                   1595:     sub render_advtools {
1.253.2.4  raeburn  1596:         my ($breadcrumbs,$legend) = @_;
1.253.2.3  raeburn  1597:         return unless     (defined $tools{'advtools'})
                   1598:                       and (scalar(@{$tools{'advtools'}}) > 0);
1.253.2.4  raeburn  1599:         my $args;
                   1600:         if ($legend) {
                   1601:             $args = {legend => $legend};
                   1602:         }
1.253.2.3  raeburn  1603:         $$breadcrumbs .= Apache::loncommon::head_subbox(
1.253.2.4  raeburn  1604:                             funclist_from_array($tools{'advtools'},$args));
1.242     droeschl 1605:     }
1.53      matthew  1606: 
1.57      matthew  1607: } # End of scope for @Crumbs
1.53      matthew  1608: 
                   1609: ############################################################
                   1610: ############################################################
                   1611: 
1.112     raeburn  1612: # Nested table routines.
                   1613: #
                   1614: # Routines to display form items in a multi-row table with 2 columns.
                   1615: # Uses nested tables to divide form elements into segments.
                   1616: # For examples of use see loncom/interface/lonnotify.pm 
                   1617: #
                   1618: # Can be used in following order: ...
                   1619: # &start_pick_box()
                   1620: # row1
                   1621: # row2
                   1622: # row3   ... etc.
1.173     raeburn  1623: # &submit_row()
1.161     raeburn  1624: # &end_pick_box()
1.112     raeburn  1625: #
                   1626: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
                   1627: # &status_select_row and &email_default_row
                   1628: #
                   1629: # Can also be used in following order:
                   1630: #
                   1631: # &start_pick_box()
                   1632: # &row_title()
                   1633: # &row_closure()
                   1634: # &row_title()
                   1635: # &row_closure()  ... etc.
                   1636: # &submit_row()
                   1637: # &end_pick_box()
                   1638: #
                   1639: # In general a &submit_row() call should proceed the call to &end_pick_box(),
                   1640: # as this routine adds a button for form submission.
1.113     raeburn  1641: # &submit_row() does not require a &row_closure after it.
1.112     raeburn  1642: #  
                   1643: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
                   1644: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
                   1645: #
                   1646: # &row_title() adds a title in the left column for each segment.
                   1647: # &row_closure() closes a row with a 1-pixel wide black line.
                   1648: #
                   1649: # &role_select_row() provides a select box from which to choose 1 or more roles 
                   1650: # &course_select_row provides ways of picking groups of courses
                   1651: #    radio buttons: all, by category or by picking from a course picker pop-up
                   1652: #      note: by category option is only displayed if a domain has implemented 
                   1653: #                selection by year, semester, department, number etc.
                   1654: #
                   1655: # &status_select_row() provides a select box from which to choose 1 or more
                   1656: #  access types (current access, prior access, and future access)  
                   1657: #
                   1658: # &email_default_row() provides text boxes for default e-mail suffixes for
                   1659: #  different authentication types in a domain.
                   1660: #
                   1661: # &row_title() and &row_closure() are called internally by the &*_select_row
                   1662: # routines, but can also be called directly to start and end rows which have 
                   1663: # needs that are not accommodated by the *_select_row() routines.    
                   1664: 
1.193     bisitz   1665: { # Start: row_count block for pick_box
                   1666: my @row_count;
                   1667: 
1.112     raeburn  1668: sub start_pick_box {
1.142     albertel 1669:     my ($css_class) = @_;
                   1670:     if (defined($css_class)) {
                   1671: 	$css_class = 'class="'.$css_class.'"';
                   1672:     } else {
                   1673: 	$css_class= 'class="LC_pick_box"';
                   1674:     }
1.193     bisitz   1675:     unshift(@row_count,0);
1.112     raeburn  1676:     my $output = <<"END";
1.142     albertel 1677:  <table $css_class>
1.112     raeburn  1678: END
                   1679:     return $output;
                   1680: }
                   1681: 
                   1682: sub end_pick_box {
1.193     bisitz   1683:     shift(@row_count);
1.112     raeburn  1684:     my $output = <<"END";
                   1685:        </table>
                   1686: END
                   1687:     return $output;
                   1688: }
                   1689: 
1.181     bisitz   1690: sub row_headline {
                   1691:     my $output = <<"END";
                   1692:            <tr><td colspan="2">
                   1693: END
                   1694:     return $output;
                   1695: }
                   1696: 
1.112     raeburn  1697: sub row_title {
1.243     amueller 1698:     my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_;
1.193     bisitz   1699:     $row_count[0]++;
                   1700:     my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.142     albertel 1701:     $css_title_class ||= 'LC_pick_box_title';
                   1702:     $css_title_class = 'class="'.$css_title_class.'"';
                   1703: 
                   1704:     $css_value_class ||= 'LC_pick_box_value';
                   1705: 
1.173     raeburn  1706:     if ($title ne '') {
                   1707:         $title .= ':';
                   1708:     }
1.112     raeburn  1709:     my $output = <<"ENDONE";
1.243     amueller 1710:            <tr class="LC_pick_box_row" $css_value_furtherAttributes> 
1.142     albertel 1711:             <td $css_title_class>
1.173     raeburn  1712: 	       $title
1.112     raeburn  1713:             </td>
1.193     bisitz   1714:             <td class="$css_value_class $css_class">
1.112     raeburn  1715: ENDONE
                   1716:     return $output;
                   1717: }
                   1718: 
                   1719: sub row_closure {
1.143     albertel 1720:     my ($no_separator) =@_;
1.113     raeburn  1721:     my $output = <<"ENDTWO";
1.112     raeburn  1722:             </td>
                   1723:            </tr>
1.143     albertel 1724: ENDTWO
                   1725:     if (!$no_separator) {
                   1726:         $output .= <<"ENDTWO";
1.112     raeburn  1727:            <tr>
1.143     albertel 1728:             <td colspan="2" class="LC_pick_box_separator">
1.112     raeburn  1729:             </td>
                   1730:            </tr>
                   1731: ENDTWO
1.143     albertel 1732:     }
1.112     raeburn  1733:     return $output;
                   1734: }
                   1735: 
1.193     bisitz   1736: } # End: row_count block for pick_box
                   1737: 
1.112     raeburn  1738: sub role_select_row {
1.147     raeburn  1739:     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
1.236     raeburn  1740:     my $crstype = 'Course';
                   1741:     if ($cdom ne '' && $cnum ne '') {
                   1742:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
                   1743:     }
1.116     raeburn  1744:     my $output;
                   1745:     if (defined($title)) {
1.142     albertel 1746:         $output = &row_title($title,$css_class);
1.116     raeburn  1747:     }
1.142     albertel 1748:     $output .= qq|
1.198     bisitz   1749:                                   <select name="roles" multiple="multiple">\n|;
1.113     raeburn  1750:     foreach my $role (@$roles) {
1.114     raeburn  1751:         my $plrole;
                   1752:         if ($role eq 'ow') {
                   1753:             $plrole = &mt('Course Owner');
1.147     raeburn  1754:         } elsif ($role eq 'cr') {
                   1755:             if ($show_separate_custom) {
                   1756:                 if ($cdom ne '' && $cnum ne '') {
                   1757:                     my %course_customroles = &course_custom_roles($cdom,$cnum);
                   1758:                     foreach my $crrole (sort(keys(%course_customroles))) {
                   1759:                         my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
                   1760:                         $output .= '  <option value="'.$crrole.'">'.$plcrrole.
                   1761:                                    '</option>';
                   1762:                     }
                   1763:                 }
                   1764:             } else {
                   1765:                 $plrole = &mt('Custom Role');
                   1766:             }
1.114     raeburn  1767:         } else {
1.236     raeburn  1768:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
1.114     raeburn  1769:         }
1.147     raeburn  1770:         if (($role ne 'cr') || (!$show_separate_custom)) {
                   1771:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1772:         }
1.112     raeburn  1773:     }
1.142     albertel 1774:     $output .= qq|                </select>\n|;
1.116     raeburn  1775:     if (defined($title)) {
                   1776:         $output .= &row_closure();
                   1777:     }
1.112     raeburn  1778:     return $output;
                   1779: }
                   1780: 
                   1781: sub course_select_row {
1.142     albertel 1782:     my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
1.237     raeburn  1783: 	$css_class,$crstype) = @_;
1.142     albertel 1784:     my $output = &row_title($title,$css_class);
1.237     raeburn  1785:     $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype);
1.169     raeburn  1786:     $output .= &row_closure();
                   1787:     return $output;
                   1788: }
                   1789: 
                   1790: sub course_selection {
1.237     raeburn  1791:     my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype) = @_;
1.169     raeburn  1792:     my $output = qq|
1.142     albertel 1793: <script type="text/javascript">
1.218     bisitz   1794: // <![CDATA[
1.112     raeburn  1795:     function coursePick (formname) {
                   1796:         for  (var i=0; i<formname.coursepick.length; i++) {
1.114     raeburn  1797:             if (formname.coursepick[i].value == 'category') {
                   1798:                 courseSet('');
                   1799:             }
1.112     raeburn  1800:             if (!formname.coursepick[i].checked) {
                   1801:                 if (formname.coursepick[i].value == 'specific') {
                   1802:                     formname.coursetotal.value = 0;
                   1803:                     formname.courselist = '';
                   1804:                 }
                   1805:             }
                   1806:         }
                   1807:     }
1.114     raeburn  1808:     function setPick (formname) {
                   1809:         for  (var i=0; i<formname.coursepick.length; i++) {
                   1810:             if (formname.coursepick[i].value == 'category') {
                   1811:                 formname.coursepick[i].checked = true;
                   1812:             }
                   1813:             formname.coursetotal.value = 0;
                   1814:             formname.courselist = '';
                   1815:         }
                   1816:     }
1.218     bisitz   1817: // ]]>
1.112     raeburn  1818: </script>
                   1819:     |;
1.237     raeburn  1820: 
                   1821:     my ($allcrs,$pickspec);
                   1822:     if ($crstype eq 'Community') {
                   1823:         $allcrs = &mt('All communities');
                   1824:         $pickspec = &mt('Pick specific communities:');
                   1825:     } else {
                   1826:         $allcrs = &mt('All courses');
                   1827:         $pickspec = &mt('Pick specific course(s):');
                   1828:     }
                   1829: 
1.112     raeburn  1830:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
1.237     raeburn  1831:                      ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).'</b>';
                   1832:         $output .= '<input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.$allcrs.'<br />';
1.112     raeburn  1833:     if ($totcodes > 0) {
                   1834:         my $numtitles = @$codetitles;
                   1835:         if ($numtitles > 0) {
1.129     raeburn  1836:             $output .= '<input type="radio" name="coursepick" value="category" onclick="coursePick(this.form);alert('."'".&mt('Choose categories, from left to right')."'".')" />'.&mt('Pick courses by category:').' <br />';
1.112     raeburn  1837:             $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
                   1838:                '<select name="'.$$codetitles[0].
1.114     raeburn  1839:                '" onChange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
1.112     raeburn  1840:                ' <option value="-1" />Select'."\n";
                   1841:             my @items = ();
                   1842:             my @longitems = ();
                   1843:             if ($$idlist{$$codetitles[0]} =~ /","/) {
1.113     raeburn  1844:                 @items = split(/","/,$$idlist{$$codetitles[0]});
1.112     raeburn  1845:             } else {
                   1846:                 $items[0] = $$idlist{$$codetitles[0]};
                   1847:             }
                   1848:             if (defined($$idlist_titles{$$codetitles[0]})) {
                   1849:                 if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
1.113     raeburn  1850:                     @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
1.112     raeburn  1851:                 } else {
                   1852:                     $longitems[0] = $$idlist_titles{$$codetitles[0]};
                   1853:                 }
                   1854:                 for (my $i=0; $i<@longitems; $i++) {
                   1855:                     if ($longitems[$i] eq '') {
                   1856:                         $longitems[$i] = $items[$i];
                   1857:                     }
                   1858:                 }
                   1859:             } else {
                   1860:                 @longitems = @items;
                   1861:             }
                   1862:             for (my $i=0; $i<@items; $i++) {
                   1863:                 $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
                   1864:             }
                   1865:             $output .= '</select></td>';
                   1866:             for (my $i=1; $i<$numtitles; $i++) {
                   1867:                 $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
                   1868:                           '<select name="'.$$codetitles[$i].
                   1869:                           '" onChange="courseSet('."'$$codetitles[$i]'".')">'."\n".
                   1870:                           '<option value="-1">&lt;-Pick '.$$codetitles[$i-1].'</option>'."\n".
                   1871:                           '</select>'."\n".
                   1872:                           '</td>';
                   1873:             }
                   1874:             $output .= '</tr></table><br />';
                   1875:         }
                   1876:     }
1.238     raeburn  1877:     $output .= '<input type="radio" name="coursepick" value="specific" onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1','$crstype'".')" />'.$pickspec.' '.$courseform.'&nbsp;&nbsp;<input type="text" value="0" size="4" name="coursetotal" /><input type="hidden" name="courselist" value="" />selected.<br />'."\n";
1.112     raeburn  1878:     return $output;
                   1879: }
                   1880: 
                   1881: sub status_select_row {
1.142     albertel 1882:     my ($types,$title,$css_class) = @_;
1.117     raeburn  1883:     my $output; 
                   1884:     if (defined($title)) {
1.142     albertel 1885:         $output = &row_title($title,$css_class,'LC_pick_box_select');
1.117     raeburn  1886:     }
1.142     albertel 1887:     $output .= qq|
1.198     bisitz   1888:                                     <select name="types" multiple="multiple">\n|;
1.113     raeburn  1889:     foreach my $status_type (sort(keys(%{$types}))) {
1.112     raeburn  1890:         $output .= '  <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
                   1891:     }
1.142     albertel 1892:     $output .= qq|                   </select>\n|; 
1.117     raeburn  1893:     if (defined($title)) {
                   1894:         $output .= &row_closure();
                   1895:     }
1.112     raeburn  1896:     return $output;
                   1897: }
                   1898: 
                   1899: sub email_default_row {
1.142     albertel 1900:     my ($authtypes,$title,$descrip,$css_class) = @_;
                   1901:     my $output = &row_title($title,$css_class);
                   1902:     $output .= $descrip.
                   1903: 	&Apache::loncommon::start_data_table().
                   1904: 	&Apache::loncommon::start_data_table_header_row().
                   1905: 	'<th>'.&mt('Authentication Method').'</th>'.
                   1906: 	'<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
                   1907: 	&Apache::loncommon::end_data_table_header_row();
1.112     raeburn  1908:     my $rownum = 0;
1.113     raeburn  1909:     foreach my $auth (sort(keys(%{$authtypes}))) {
1.112     raeburn  1910:         my ($userentry,$size);
                   1911:         if ($auth =~ /^krb/) {
                   1912:             $userentry = '';
                   1913:             $size = 25;
                   1914:         } else {
                   1915:             $userentry = 'username@';
                   1916:             $size = 15;
                   1917:         }
1.142     albertel 1918:         $output .= &Apache::loncommon::start_data_table_row().
                   1919: 	    '<td>  '.$$authtypes{$auth}.'</td>'.
                   1920: 	    '<td align="right">'.$userentry.
                   1921: 	    '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
                   1922: 	    &Apache::loncommon::end_data_table_row();
1.112     raeburn  1923:     }
1.142     albertel 1924:     $output .= &Apache::loncommon::end_data_table();
1.112     raeburn  1925:     $output .= &row_closure();
                   1926:     return $output;
                   1927: }
                   1928: 
                   1929: 
                   1930: sub submit_row {
1.142     albertel 1931:     my ($title,$cmd,$submit_text,$css_class) = @_;
                   1932:     my $output = &row_title($title,$css_class,'LC_pick_box_submit');
1.112     raeburn  1933:     $output .= qq|
                   1934:              <br />
                   1935:              <input type="hidden" name="command" value="$cmd" />
                   1936:              <input type="submit" value="$submit_text"/> &nbsp;
                   1937:              <br /><br />
1.142     albertel 1938:             \n|;
1.112     raeburn  1939:     return $output;
                   1940: }
1.1       stredwic 1941: 
1.147     raeburn  1942: sub course_custom_roles {
                   1943:     my ($cdom,$cnum) = @_;
                   1944:     my %returnhash=();
                   1945:     my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   1946:     foreach my $person (sort(keys(%coursepersonnel))) {
                   1947:         my ($role) = ($person =~ /^([^:]+):/);
                   1948:         my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   1949:         if ($end == -1 && $start == -1) {
                   1950:             next;
                   1951:         }
                   1952:         if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
                   1953:             $returnhash{$role} ++;
                   1954:         }
                   1955:     }
                   1956:     return %returnhash;
                   1957: }
                   1958: 
                   1959: 
1.119     raeburn  1960: ##############################################
                   1961: ##############################################
1.179     raeburn  1962: 
                   1963: # topic_bar
                   1964: #
1.248     wenzelju 1965: # Generates a div containing an (optional) number with a white background followed by a 
1.240     raeburn  1966: # title with a background color defined in the corresponding CSS: LC_topic_bar
                   1967: # Inputs:
1.248     wenzelju 1968: # 1. number to display.
                   1969: #    If input for number is empty only the title will be displayed. 
1.240     raeburn  1970: # 2. title text to display.
                   1971: # Outputs - a scalar containing html mark-up for the div.
                   1972: 
1.179     raeburn  1973: sub topic_bar {
1.248     wenzelju 1974:     my ($num,$title) = @_;
                   1975:     my $number = '';
                   1976:     if ($num ne '') {
                   1977:         $number = '<span>'.$num.'</span>';
1.239     amueller 1978:     }
1.248     wenzelju 1979:     return '<div class="LC_topic_bar">'.$number.$title.'</div>';
1.179     raeburn  1980: }
                   1981: 
                   1982: ##############################################
                   1983: ##############################################
1.119     raeburn  1984: # echo_form_input
                   1985: #
                   1986: # Generates html markup to add form elements from the referrer page
                   1987: # as hidden form elements (values encoded) in the new page.
                   1988: #
                   1989: # Intended to support two types of use 
                   1990: # (a) to allow backing up to earlier pages in a multi-page 
                   1991: # form submission process using a breadcrumb trail.
                   1992: #
                   1993: # (b) to allow the current page to be reloaded with form elements
                   1994: # set on previous page to remain unchanged.  An example would
                   1995: # be where the a page containing a dynamically-built table of data is 
                   1996: # is to be redisplayed, with only the sort order of the data changed. 
                   1997: #  
                   1998: # Inputs:
                   1999: # 1. Reference to array of form elements in the submitted form on 
                   2000: # the referrer page which are to be excluded from the echoed elements.
                   2001: #
                   2002: # 2. Reference to array of regular expressions, which if matched in the  
                   2003: # name of the form element n the referrer page will be omitted from echo. 
                   2004: #
                   2005: # Outputs: A scalar containing the html markup for the echoed form
                   2006: # elements (all as hidden elements, with values encoded). 
                   2007: 
                   2008: 
                   2009: sub echo_form_input {
                   2010:     my ($excluded,$regexps) = @_;
                   2011:     my $output = '';
                   2012:     foreach my $key (keys(%env)) {
                   2013:         if ($key =~ /^form\.(.+)$/) {
                   2014:             my $name = $1;
                   2015:             my $match = 0;
                   2016:             if ((!@{$excluded}) || (!grep/^$name$/,@{$excluded})) {
                   2017:                 if (defined($regexps)) {
                   2018:                     if (@{$regexps} > 0) {
                   2019:                         foreach my $regexp (@{$regexps}) {
                   2020:                             if ($name =~ /\Q$regexp\E/) {
                   2021:                                 $match = 1;
                   2022:                                 last;
                   2023:                             }
                   2024:                         }
                   2025:                     }
                   2026:                 }
                   2027:                 if (!$match) {
                   2028:                     if (ref($env{$key})) {
                   2029:                         foreach my $value (@{$env{$key}}) {
                   2030:                             $value = &HTML::Entities::encode($value,'<>&"');
                   2031:                             $output .= '<input type="hidden" name="'.$name.
                   2032:                                              '" value="'.$value.'" />'."\n";
                   2033:                         }
                   2034:                     } else {
                   2035:                         my $value = &HTML::Entities::encode($env{$key},'<>&"');
                   2036:                         $output .= '<input type="hidden" name="'.$name.
                   2037:                                              '" value="'.$value.'" />'."\n";
                   2038:                     }
                   2039:                 }
                   2040:             }
                   2041:         }
                   2042:     }
                   2043:     return $output;
                   2044: }
                   2045: 
                   2046: ##############################################
                   2047: ##############################################
                   2048: # set_form_elements
                   2049: #
                   2050: # Generates javascript to set form elements to values based on
                   2051: # corresponding values for the same form elements when the page was
                   2052: # previously submitted.
                   2053: #     
                   2054: # Last submission values are read from hidden form elements in referring 
                   2055: # page which have the same name, i.e., generated by &echo_form_input(). 
                   2056: #
                   2057: # Intended to be called by onload event.
                   2058: #
1.121     raeburn  2059: # Inputs:
                   2060: # (a) Reference to hash of echoed form elements to be set.
1.119     raeburn  2061: #
                   2062: # In the hash, keys are the form element names, and the values are the
                   2063: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
                   2064: # hidden).
1.121     raeburn  2065: #
                   2066: # (b) Optional reference to hash of stored elements to be set.
                   2067: #
                   2068: # If the page being displayed is a page which permits modification of
                   2069: # previously stored data, e.g., the first page in a multi-page submission,
                   2070: # then if stored is supplied, form elements will be set to the last stored
                   2071: # values.  If user supplied values are also available for the same elements
                   2072: # these will replace the stored values. 
                   2073: #        
1.119     raeburn  2074: # Output:
                   2075: #  
                   2076: # javascript function - set_form_elements() which sets form elements,
                   2077: # expects an argument: formname - the name of the form according to 
                   2078: # the DOM, e.g., document.compose
                   2079: 
                   2080: sub set_form_elements {
1.121     raeburn  2081:     my ($elements,$stored) = @_;
                   2082:     my %values;
1.119     raeburn  2083:     my $output .= 'function setFormElements(courseForm) {
1.121     raeburn  2084: ';
                   2085:     if (defined($stored)) {
                   2086:         foreach my $name (keys(%{$stored})) {
                   2087:             if (exists($$elements{$name})) {
                   2088:                 if (ref($$stored{$name}) eq 'ARRAY') {
                   2089:                     $values{$name} = $$stored{$name};
                   2090:                 } else {
                   2091:                     @{$values{$name}} = ($$stored{$name});
                   2092:                 }
                   2093:             }
                   2094:         }
                   2095:     }
                   2096: 
1.119     raeburn  2097:     foreach my $key (keys(%env)) {
                   2098:         if ($key =~ /^form\.(.+)$/) {
                   2099:             my $name = $1;
                   2100:             if (exists($$elements{$name})) {
1.121     raeburn  2101:                 @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
                   2102:             }
                   2103:         }
                   2104:     }
                   2105: 
                   2106:     foreach my $name (keys(%values)) {
                   2107:         for (my $i=0; $i<@{$values{$name}}; $i++) {
                   2108:             $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
                   2109:             $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
                   2110:             $values{$name}[$i] =~ s/"/\\"/g;
                   2111:         }
1.234     raeburn  2112:         if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) {
1.121     raeburn  2113:             my $numvalues = @{$values{$name}};
                   2114:             if ($numvalues > 1) {
                   2115:                 my $valuestring = join('","',@{$values{$name}});
                   2116:                 $output .= qq|
1.119     raeburn  2117:   var textvalues = new Array ("$valuestring");
1.147     raeburn  2118:   var total = courseForm.elements['$name'].length;
1.119     raeburn  2119:   if (total > $numvalues) {
                   2120:       total = $numvalues;
                   2121:   }    
                   2122:   for (var i=0; i<total; i++) {
1.147     raeburn  2123:       courseForm.elements['$name']\[i].value = textvalues[i];
1.119     raeburn  2124:   }
                   2125: |;
1.121     raeburn  2126:             } else {
                   2127:                 $output .= qq|
1.147     raeburn  2128:   courseForm.elements['$name'].value = "$values{$name}[0]";
1.119     raeburn  2129: |;
1.121     raeburn  2130:             }
                   2131:         } else {
                   2132:             $output .=  qq|
1.147     raeburn  2133:   var elementLength = courseForm.elements['$name'].length;
1.119     raeburn  2134:   if (elementLength==undefined) {
                   2135: |;
1.121     raeburn  2136:             foreach my $value (@{$values{$name}}) {
                   2137:                 if ($$elements{$name} eq 'selectbox') {
                   2138:                     $output .=  qq|
1.147     raeburn  2139:       if (courseForm.elements['$name'].options[0].value == "$value") {
                   2140:           courseForm.elements['$name'].options[0].selected = true;
1.119     raeburn  2141:       }|;
1.121     raeburn  2142:                 } elsif (($$elements{$name} eq 'radio') ||
                   2143:                          ($$elements{$name} eq 'checkbox')) {
                   2144:                     $output .= qq|
1.147     raeburn  2145:       if (courseForm.elements['$name'].value == "$value") {
1.148     albertel 2146:           courseForm.elements['$name'].checked = true;
1.234     raeburn  2147:       } else {
                   2148:           courseForm.elements['$name'].checked = false;
1.119     raeburn  2149:       }|;
1.121     raeburn  2150:                 }
                   2151:             }
                   2152:             $output .= qq|
1.119     raeburn  2153:   }
                   2154:   else {
1.147     raeburn  2155:       for (var i=0; i<courseForm.elements['$name'].length; i++) {
1.119     raeburn  2156: |;
1.121     raeburn  2157:             if ($$elements{$name} eq 'selectbox') {
                   2158:                 $output .=  qq|
1.147     raeburn  2159:           courseForm.elements['$name'].options[i].selected = false;|;
1.121     raeburn  2160:             } elsif (($$elements{$name} eq 'radio') || 
                   2161:                      ($$elements{$name} eq 'checkbox')) {
                   2162:                 $output .= qq|
1.147     raeburn  2163:           courseForm.elements['$name']\[i].checked = false;|; 
1.121     raeburn  2164:             }
                   2165:             $output .= qq|
1.119     raeburn  2166:       }
1.147     raeburn  2167:       for (var j=0; j<courseForm.elements['$name'].length; j++) {
1.119     raeburn  2168: |;
1.121     raeburn  2169:             foreach my $value (@{$values{$name}}) {
                   2170:                 if ($$elements{$name} eq 'selectbox') {
                   2171:                     $output .=  qq|
1.147     raeburn  2172:           if (courseForm.elements['$name'].options[j].value == "$value") {
                   2173:               courseForm.elements['$name'].options[j].selected = true;
1.119     raeburn  2174:           }|;
1.121     raeburn  2175:                 } elsif (($$elements{$name} eq 'radio') ||
                   2176:                          ($$elements{$name} eq 'checkbox')) { 
                   2177:                       $output .= qq|
1.147     raeburn  2178:           if (courseForm.elements['$name']\[j].value == "$value") {
                   2179:               courseForm.elements['$name']\[j].checked = true;
1.119     raeburn  2180:           }|;
1.121     raeburn  2181:                 }
                   2182:             }
                   2183:             $output .= qq|
1.119     raeburn  2184:       }
                   2185:   }
                   2186: |;
                   2187:         }
                   2188:     }
                   2189:     $output .= "
1.235     raeburn  2190:     return;
1.119     raeburn  2191: }\n";
                   2192:     return $output;
                   2193: }
                   2194: 
1.158     raeburn  2195: ##############################################
                   2196: ##############################################
                   2197: 
                   2198: # javascript_valid_email
                   2199: #
                   2200: # Generates javascript to validate an e-mail address.
                   2201: # Returns a javascript function which accetps a form field as argumnent, and
                   2202: # returns false if field.value does not satisfy two regular expression matches
                   2203: # for a valid e-mail address.  Backwards compatible with old browsers without
                   2204: # support for javascript RegExp (just checks for @ in field.value in this case). 
                   2205: 
                   2206: sub javascript_valid_email {
                   2207:     my $scripttag .= <<'END';
                   2208: function validmail(field) {
                   2209:     var str = field.value;
                   2210:     if (window.RegExp) {
                   2211:         var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
                   2212:         var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
                   2213:         var reg1 = new RegExp(reg1str);
                   2214:         var reg2 = new RegExp(reg2str);
                   2215:         if (!reg1.test(str) && reg2.test(str)) {
                   2216:             return true;
                   2217:         }
                   2218:         return false;
                   2219:     }
                   2220:     else
                   2221:     {
                   2222:         if(str.indexOf("@") >= 0) {
                   2223:             return true;
                   2224:         }
                   2225:         return false;
                   2226:     }
                   2227: }
                   2228: END
                   2229:     return $scripttag;
                   2230: }
                   2231: 
1.219     droeschl 2232: 
                   2233: # USAGE: htmltag(element, content, {attribute => value,...});
                   2234: #
                   2235: # EXAMPLES: 
                   2236: #  - htmltag('a', 'this is an anchor', {href  => 'www.example.com', 
                   2237: #                                       title => 'this is a title'})
                   2238: #
                   2239: #  - You might want to set up needed tags like: 
                   2240: #
                   2241: #     my $h3  = sub { return htmltag( "h3",  @_ ) };
                   2242: #
                   2243: #    ... and use them: $h3->("This is a headline")
                   2244: #
                   2245: #  - To set up a couple of tags, see sub inittags
                   2246: #
                   2247: # NOTES:
                   2248: # - Empty elements, such as <br/> are correctly terminated, 
                   2249: #   i.e. htmltag('br') returns <br/> 
                   2250: # - Empty attributes (title="") are filtered out.
                   2251: # - The function will not check for deprecated attributes.
                   2252: #
                   2253: # OUTPUT: content enclosed in xhtml conform tags
                   2254: sub htmltag{
                   2255:     return
                   2256:         qq|<$_[0]|
                   2257:         . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } )
                   2258:         . ($_[1] ? qq|>$_[1]</$_[0]>| : qq|/>|). "\n";
                   2259: };
                   2260: 
                   2261: 
                   2262: # USAGE: inittags(@tags);
                   2263: #
                   2264: # EXAMPLES:
1.253.2.3  raeburn  2265: #  - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) )
1.219     droeschl 2266: #    $h1->("This is a headline") #Returns: <h1>This is a headline</h1>
                   2267: #
                   2268: # NOTES: See sub htmltag for further information.
                   2269: #
                   2270: # OUTPUT: List of subroutines. 
                   2271: sub inittags {
                   2272:     my @tags = @_;
                   2273:     return map { my $tag = $_;
                   2274:                  sub { return htmltag( $tag, @_ ) }
                   2275:                } @tags;
                   2276: }
                   2277: 
                   2278: 
1.231     droeschl 2279: # USAGE: scripttag(scriptcode, [start|end|both]);
1.229     droeschl 2280: #
                   2281: # EXAMPLES: 
1.231     droeschl 2282: #  - scripttag("alert('Hello World!')", 'both') 
                   2283: #    returns:
                   2284: #    <script type="text/javascript">
                   2285: #    // BEGIN LON-CAPA Internal
                   2286: #    alert(Hello World!')
                   2287: #    // END LON-CAPA Internal
                   2288: #    </script>
1.229     droeschl 2289: #
                   2290: # NOTES:
                   2291: # - works currently only for javascripts
                   2292: #
1.231     droeschl 2293: # OUTPUT: 
                   2294: # Scriptcode properly enclosed in <script> and CDATA tags (and LC
                   2295: # Internal markers if 2nd argument is given)
1.229     droeschl 2296: sub scripttag {
1.231     droeschl 2297:     my ( $content, $marker ) = @_;
                   2298:     return unless defined $content;
                   2299: 
                   2300:     my $begin = "\n// BEGIN LON-CAPA Internal\n";
                   2301:     my $end   = "\n// END LON-CAPA Internal\n";
                   2302: 
                   2303:     if ($marker) {
                   2304:         $content  = $begin . $content if $marker eq 'start' or $marker eq 'both';
                   2305:         $content .= $end              if $marker eq 'end'   or $marker eq 'both';
                   2306:     }
                   2307: 
1.229     droeschl 2308:     $content = "\n// <![CDATA[\n$content\n// ]]>\n";
1.231     droeschl 2309: 
                   2310:     return htmltag('script', $content, {type => 'text/javascript'});
1.229     droeschl 2311: };
                   2312: 
                   2313: 
1.253.2.3  raeburn  2314: =item list_from_array( \@array, { listattr =>{}, itemattr =>{} } )
                   2315: 
                   2316: Constructs a XHTML list from \@array.
                   2317: 
                   2318: input:
                   2319: 
                   2320: =over
                   2321: 
                   2322: =item \@array
                   2323: 
                   2324: A reference to the array containing text that will be wrapped in <li></li> tags.
                   2325: 
                   2326: =item { listattr => {}, itemattr =>{} }
                   2327: 
                   2328: Attributes for <ul> and <li> passed in as hash references.
                   2329: See htmltag() for more details.
                   2330: 
                   2331: =back
                   2332: 
                   2333: returns: XHTML list as String.
                   2334: 
                   2335: =cut
                   2336: 
                   2337: # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
                   2338: sub list_from_array {
                   2339:     my ($items, $args) = @_;
                   2340:     return unless scalar @$items;
                   2341:     my ($ul, $li) = inittags( qw(ul li) );
                   2342:     my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
                   2343:     return $ul->( $listitems, $args->{listattr} );
                   2344: }
                   2345: 
                   2346: 
1.183     droeschl 2347: ##############################################
                   2348: ##############################################
                   2349: 
                   2350: # generate_menu
                   2351: #
                   2352: # Generates html markup for a menu. 
                   2353: #
                   2354: # Inputs:
                   2355: # An array of following structure:
                   2356: #   ({	categorytitle => 'Categorytitle',
                   2357: #	items => [
1.201     droeschl 2358: #		    {	
                   2359: #           linktext    =>	'Text to be displayed',
                   2360: #			url	        =>	'URL the link is pointing to, i.e. /adm/site?action=dosomething',
1.183     droeschl 2361: #			permission  =>	'Contains permissions as returned from lonnet::allowed(),
1.201     droeschl 2362: #					         must evaluate to true in order to activate the link',
1.184     droeschl 2363: #			icon        =>  'icon filename',
1.186     droeschl 2364: #			alttext	    =>	'alt text for the icon',
1.183     droeschl 2365: #			help	    =>	'Name of the corresponding helpfile',
                   2366: #			linktitle   =>	'Description of the link (used for title tag)'
                   2367: #		    },
                   2368: #		    ...
                   2369: #		]
                   2370: #   }, 
                   2371: #   ...
                   2372: #   )
                   2373: #
                   2374: # Outputs: A scalar containing the html markup for the menu.
                   2375: 
                   2376: sub generate_menu {
                   2377:     my @menu = @_;
1.201     droeschl 2378:     # subs for specific html elements
1.219     droeschl 2379:     my ($h3, $div, $ul, $li, $a, $img) = inittags( qw(h3 div ul li a img) ); 
1.201     droeschl 2380:     
                   2381:     my @categories; # each element represents the entire markup for a category
                   2382:    
                   2383:     foreach my $category (@menu) {
                   2384:         my @links;  # contains the links for the current $category
                   2385:         foreach my $link (@{$$category{items}}) {
                   2386:             next unless $$link{permission};
                   2387:             
                   2388:             # create the markup for the current $link and push it into @links.
                   2389:             # each entry consists of an image and a text optionally followed 
                   2390:             # by a help link.
1.253.2.3  raeburn  2391:             my $src;
                   2392:             if ($$link{icon} ne '') {
                   2393:                 $src = '/res/adm/pages/'.$$link{icon};
                   2394:             }
1.232     raeburn  2395:             push(@links,$li->(
1.201     droeschl 2396:                         $a->(
                   2397:                             $img->("", {
                   2398:                                 class => "LC_noBorder LC_middle",
1.253.2.3  raeburn  2399:                                 src   => $src,
1.202     droeschl 2400:                                 alt   => mt(defined($$link{alttext}) ?
                   2401:                                 $$link{alttext} : $$link{linktext})
1.201     droeschl 2402:                             }), {
                   2403:                             href  => $$link{url},
1.202     droeschl 2404:                             title => mt($$link{linktitle})
1.201     droeschl 2405:                             }).
1.202     droeschl 2406:                         $a->(mt($$link{linktext}), {
1.201     droeschl 2407:                             href  => $$link{url},
1.202     droeschl 2408:                             title => mt($$link{linktitle}),
1.201     droeschl 2409:                             class => "LC_menubuttons_link"
                   2410:                             }).
                   2411:                          (defined($$link{help}) ? 
                   2412:                          Apache::loncommon::help_open_topic($$link{help}) : ''),
1.232     raeburn  2413:                          {class => "LC_menubuttons_inline_text"}));
1.201     droeschl 2414:         }
                   2415: 
                   2416:         # wrap categorytitle in <h3>, concatenate with 
                   2417:         # joined and in <ul> tags wrapped @links
                   2418:         # and wrap everything in an enclosing <div> and push it into
                   2419:         # @categories
                   2420:         # such that each element looks like:
                   2421:         # <div><h3>title</h3><ul><li>...</li>...</ul></div>
                   2422:         # the category won't be added if there aren't any links
1.232     raeburn  2423:         push(@categories, 
1.202     droeschl 2424:             $div->($h3->(mt($$category{categorytitle}), {class=>"LC_hcell"}).
1.201     droeschl 2425:             $ul->(join('' ,@links),  {class =>"LC_ListStyleNormal" }),
1.232     raeburn  2426:             {class=>"LC_Box LC_400Box"})) if scalar(@links);
1.183     droeschl 2427:     }
1.201     droeschl 2428: 
                   2429:     # wrap the joined @categories in another <div> (column layout)
                   2430:     return $div->(join('', @categories), {class => "LC_columnSection"});
1.183     droeschl 2431: }
1.176     foxr     2432: 
1.224     bisitz   2433: ##############################################
                   2434: ##############################################
                   2435: 
                   2436: =pod
                   2437: 
                   2438: =item &start_funclist
                   2439: 
                   2440: Start list of available functions
                   2441: 
                   2442: Typically used to offer a simple list of available functions
                   2443: at top or bottom of page.
                   2444: All available functions/actions for the current page
                   2445: should be included in this list.
                   2446: 
                   2447: If the optional headline text is not provided, a default text will be used.
                   2448: 
                   2449: 
                   2450: Related routines:
                   2451: =over 4
                   2452: add_item_funclist
                   2453: end_funclist
                   2454: =back
                   2455: 
                   2456: 
                   2457: Inputs: (optional) headline text
                   2458: 
                   2459: Returns: HTML code with function list start
                   2460: 
                   2461: =cut
                   2462: 
                   2463: ##############################################
                   2464: ##############################################
                   2465: 
                   2466: sub start_funclist {
                   2467:     my($legendtext)=@_;
                   2468:     $legendtext=&mt('Functions') if !$legendtext;
1.244     droeschl 2469:     return '<ul class="LC_funclist"><li style="font-weight:bold; margin-left:0.8em;">'.$legendtext.'</li>'."\n";
1.224     bisitz   2470: }
                   2471: 
                   2472: 
                   2473: ##############################################
                   2474: ##############################################
                   2475: 
                   2476: =pod
                   2477: 
                   2478: =item &add_item_funclist
                   2479: 
                   2480: Adds an item to the list of available functions
                   2481: 
                   2482: Related routines:
                   2483: =over 4
                   2484: start_funclist
                   2485: end_funclist
                   2486: =back
                   2487: 
                   2488: Inputs: content item with text and link to function
                   2489: 
                   2490: Returns: HTML code with list item for funclist
                   2491: 
                   2492: =cut
                   2493: 
                   2494: ##############################################
                   2495: ##############################################
                   2496: 
                   2497: sub add_item_funclist {
                   2498:     my($content) = @_;
                   2499:     return '<li>'.$content.'</li>'."\n";
                   2500: }
                   2501: 
                   2502: =pod
                   2503: 
                   2504: =item &end_funclist
                   2505: 
                   2506: End list of available functions
                   2507: 
                   2508: Related routines:
                   2509: =over 4
                   2510: start_funclist
                   2511: add_item_funclist
                   2512: =back
                   2513: 
                   2514: Inputs: ./.
                   2515: 
                   2516: Returns: HTML code with function list end
                   2517: =cut
                   2518: 
                   2519: sub end_funclist {
1.246     bisitz   2520:     return "</ul>\n";
1.224     bisitz   2521: }
                   2522: 
1.253.2.3  raeburn  2523: =pod
                   2524: 
                   2525: =item funclist_from_array( \@array, {legend => 'text for legend'} )
                   2526: 
                   2527: Constructs a XHTML list from \@array with the first item being visually
                   2528: highlighted and set to the value of legend or 'Functions' if legend is
                   2529: empty.
                   2530: 
                   2531: =over
                   2532: 
                   2533: =item \@array
                   2534: 
                   2535: A reference to the array containing text that will be wrapped in <li></li> tags.
                   2536: 
                   2537: =item { legend => 'text' }
                   2538: 
                   2539: A string that's used as visually highlighted first item. 'Functions' is used if
                   2540: it's value evaluates to false.
                   2541: 
                   2542: =back
                   2543: 
                   2544: returns: XHTML list as string.
                   2545: 
                   2546: =back
                   2547: 
                   2548: =cut
                   2549: 
                   2550: sub funclist_from_array {
                   2551:     my ($items, $args) = @_;
                   2552:     $args->{legend} ||= mt('Functions');
                   2553:     return list_from_array( [$args->{legend}, @$items],
                   2554:                { listattr => {class => 'LC_funclist'} });
                   2555: }
                   2556: 
1.1       stredwic 2557: 1;
1.23      matthew  2558: 
1.1       stredwic 2559: __END__

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