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

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

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