File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.253: download - view: text, annotated - select for diffs
Thu Dec 3 02:13:28 2009 UTC (14 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD, GCI_3
Bug #2069 - do not turn hard-coded <a>-links into link-links (and thus make a mess)

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

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