File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.249: download - view: text, annotated - select for diffs
Tue Nov 24 06:13:20 2009 UTC (14 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Typo.

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

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