File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.182.4.13: download - view: text, annotated - select for diffs
Fri Mar 19 22:34:23 2010 UTC (14 years, 2 months ago) by raeburn
Branches: version_2_9_X
CVS tags: version_2_9_1, version_2_9_0, version_2_8_99_1
Diff to branchpoint 1.182: preferred, unified
- Backport 1.266, 1.269.

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

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