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

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

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